how to append divs to a specific div in jquery? - javascript

I am trying to dynamically fadeIn divs with a specific height and width and the same Id to a specific div with class myBox and randomly position them in myBox using the append() function. However divs are being appended inside and outside myBox.
This is my code. What is wrong?
var xx = Math.random() * 100;
for (var i = 0; i < xx; i++) {
var $newdiv1 = $("<div id='object1' style='width: 100px; height: 100px; background: red ;'></div>");
var top = Math.random() * 700 - 30;
var left = Math.random() * 1200;
$($newdiv1).css({
"top": top,
"left": left
});
$($newdiv1).css('background-color', getRandomColor);
$(".myBox").append($newdiv1).fadeIn("slow");
}

By reviewing your question I think Rory's comment gives you the answer, but I just enhaced it. Need to set overflow: hidden property of css on main div to stop showing the child objects outside of main div.
Please review the snippet, or Fiddle here. Just added background color and opacity for better presentation.
$(function(){
var xx = Math.random() * 100;
for (var i = 0; i < xx; i++) {
var $newdiv1 = $("<div id='object1' style='width: 100px; height: 100px; background: red ;'></div>");
var top = Math.random() * 700 - 30;
var left = Math.random() * 1200;
$($newdiv1).css({
"top": top,
"left": left
});
$($newdiv1).css('background-color', '#C00'); //getRandomColor);
$(".myBox").append($newdiv1).fadeIn("slow");
}
});
.myBox {
width: 500px;
height: 300px;
position: relative;
background-color: orange;
overflow: hidden;
}
.myBox div {
position: absolute;
opacity: 0.5;
border: 1px solid green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myBox"></div>
Hope this will help you.

Appending seems to be done correctly, but the first problem I can see here is that you are setting top and left attributes, but position attribute is not set.
You should add to your stylesheet something that will specify position attribute for the main container and child divs.
Example:
.myBox {
position: absolute;
}
.myBox div {
position: relative;
}
Also another thing. You specify $newdiv1 as jQuery object:
var $newdiv1 = $(...)
And then you again wrap it with $(). This should be enough:
$newdiv1.css({
"top": top,
"left": left
});
$newdiv1.css('background-color', getRandomColor);

Related

Is there any way to change a div size on scroll using intersectionObserver?

I'm trying to change the size (or scale) of a div while scrolling.
This div has a .8 scale attached to it css. I'd like to reach a scale of 1 progressively while scrolling.
IntersectionObserver seems to be a good choice to work with instead of scroll event but i don't know if i can change the state of an element using it.
You can change the scale of a div using.
document.getElementById("scaledDiv").style.transform = "scale(1)";
The scroll event should do what you want it to do. You can continue to add more if statements and check how many pixels they are scrolling to change it gradually to 1 or even back to 0.8 when they scroll back up. The 50 below represents 50 pixels from the top of the page.
window.onscroll = function() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
// They are scrolling past a certain position
document.getElementById("scaledDiv").style.transform = "scale(1)";
} else {
// They are scrolling back
}
};
I hope this will help you:
const container = document.querySelector('.container');
const containerHeight = container.scrollHeight;
const iWillExpand = document.querySelector('.iWillExpand');
container.onscroll = function(e) {
iWillExpand.style.transform = `scale(${0.8 + 0.2 * container.scrollTop / (containerHeight - 300)})`;
};
.container {
height: 300px;
width: 100%;
overflow-y: scroll;
}
.scrollMe {
height: 1500px;
width: 100%;
}
.iWillExpand {
position: fixed;
width: 200px;
height: 200px;
top: 10px;
left: 10px;
background-color: aqua;
transform: scale(0.8);
}
<div class='container'>
<div class='scrollMe' />
<div class='iWillExpand' />
</div>

DOM Coordinates are wrong when using CSS Transformations

I'm trying to solve how to get the correct coordinates and movement of the element but find that the CSS Transformation doesn't align with the elements DOM coordinates.
I've tried to also change the properties of the element's CSS Transformation via the JS code itself.
The problem you can see in the demo is that the element doesn't reach all four corners of the #wrap div.
Is it also better to incorporate a skew or perspective property rather than rotations? I've just read Top & Left position with Transform Rotate (posted as a duplicated question), but this doesn't explain how to rotation of this example's prespective would work?
HTML
<div id="wrap">
<div id="thing"></div>
</div>
JS
$(function() {
$("#wrap").click(function(e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
document.getElementById("thing").style.left = relativeX + "px";
document.getElementById("thing").style.top = relativeY + "px";
document.getElementById("thing").innerHTML = relativeX + "<br />" + relativeY;
});
});
CSS
#wrap {
height: 300px;
width: 500px;
background: green;
position: relative;
overflow: hidden;
transform: rotateX(60deg) rotateZ(-30deg);
}
#thing {
background: blue;
width: 50px;
height: 50px;
position: absolute;
transition: 1s;
left: 0;
top: 0;
}
Live: https://jsfiddle.net/h9ad4k63/

Styles apply just to first two slides

I 'm trying to do kind of slideshow on the background using two img tags. I have a couple of random images, so I have a javascript function to get a random name. But the main problem is: when I zoom or resize window first two slides crop well and display without any problem, but after that every slide is changing if I try to resize the window or zoom in-out.
Here you can see that bug: cullycross.github.io(nevermind about big images, im gonna resize them)
Here is my code:
function randomBackground () {
var active = $('#background .active');
var next = ($('#background .active').next().length > 0) ? $('#background .active').next() : $('#background img:first');
next.attr('src', getRandomName());
var imgHeight = next.height();
var windowHeight = $(window).height();
var diff = imgHeight - windowHeight;
if(diff > 0) {
next.css('top', -diff*0.6);
}
next.css('z-index', 2);
active.fadeOut(1500, function() {
active.css('z-index', 1).show().removeClass('active');
next.css('z-index', 3).addClass('active');
})
}
window.onload = function() {
$('#background .active').attr('src', getRandomName());
$('#background').fadeIn(1500);
setInterval(randomBackground, 5000)
}
Here is css:
#background {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
overflow: hidden;
}
#background img {
position: absolute;
z-index: 1;
float: left;
bottom: 0px;
left: 0px;
top: 0px;
height: auto;
width: 100%;
}
#background img.active {
z-index: 3;
}
Here is part of html:
<div id="background">
<img id="current-image" class="active" />
<img id="next-image" />
</div>
It seem to affect only the images loaded after first run.
Try adding images directly into html, using a
<ul><li><img ...></li></ul>
structure, and get the image from there.
You should decrease the fadeout delay. The problem is caused from the browser since the delay is big it can't handle both fadeout and zoom in/out
active.fadeOut(300, function() {
active.css('z-index', 1).show().removeClass('active');
next.css('z-index', 3).addClass('active');
})
And try to use light size pictures, with the same aspect ratio
I didn't found an answer, but I found a library, that makes possible that thing, that I want. Thx to https://github.com/srobbin/jquery-backstretch

div stay fixed at a certain point onscroll

There is a div, style fixed 60px from top. I want when I scroll down and the distance of div from top reached 10px, the div stop there for the rest of scrolling also when I scroll up it goes back to the old style 60px from top. I did a lot of search but I did not found anything like this. But there is a code which calculate distance from top:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);
Here's one way to do it using pure javascript. You can replace some of the selectors like document.getElementById with jQuery selectors like $("id") if you like.
window.onscroll = function(){
var el = document.getElementById('sticky'),
s = window.pageYOffset || document.documentElement.scrollTop, // how much page is scrolled
t = document.getElementById('main').getBoundingClientRect().top; // top of main div
if(s > t){
el.style.position = 'fixed'; //make position fixed instead of absolute
}else{
el.style.position = ''; //clear styles if back to original position
}
}
body {
min-height: 200em;
margin: 0;
padding: 0;
}
header {
background: black;
color: white;
padding: .5em;
}
#main { position: relative; } /* important so the sticky box positions relative to this */
#sticky {
background: cornflowerblue;
padding: .5em;
position: absolute;
right: 1em;
top: 1em;
width: 10em;
color: white;
}
<header>This is just a page header or toolbar.</header>
<section id="main">
<div id="sticky">This should stick to the top when scrolled.</div>
</section>
Here's a jQuery solution. If we're more than 10px from the top of the page add a is-sticky class to the element which you can then style with CSS.
// store the element in a variable
var element = $('.item'),
visible = false;
// on scroll
$(window).scroll(function() {
/**
* store the scroll distance in px
* from the top of the viewport
*/
var scroll = $(window).scrollTop();
/**
* if the scroll is greater than or equal
* to 10px add a class of .is-sticky to the element
* otherwise we're less than 10px from the top
* of the document and therefore don't want
* the element to have the .is-sticky class
*/
if(scroll >= 10) {
if(!visible) {
element.addClass('is-sticky');
visible = true;
}
} else {
if(visible) {
element.removeClass('is-sticky');
visible = false;
}
}
});

How do I dynamically change the css of an element that runs offscreen to make it stay onscreen?

I have what is for all intents a mouseover tooltip. It lives on multiple page elements (dynamically generated, so I never know how many there will be or what their positions are.)
I've had complaints that on lower-resolution screens, the tooltips on items in the rightmost column of elements run offscreen. Since I don't know the position of the parent item when it's created, I need a way to detect (before the mouseover actually happens) that the tooltip div will partially be offscreen when displayed, and change the css accordingly.
I know what the css needs to be; what I'm having trouble with is the detecting part. I've seen a few questions that are similar, but the solutions all involve using prototype or jquery plugins. I'm limited to core jquery (or just plain javascript) on this project.
Any pointers out there?
Here is a quick demo I put together on jsFiddle: http://jsfiddle.net/2gGrd/
HTML:
<p class="left">Left</p>
<p class="center">Center</p>
<p class="right">Right</p>​
CSS:
p {
position: absolute;
top: 50%;
}
.left {
left: 0;
}
.center {
left: 50%;
}
.right {
right: 0;
}
.toolTip {
width: 100px;
height: 25px;
background: red;
color: green;
position: absolute;
}
JavaScript:
var tip;
$('p').hover(function() {
$(this).css('color', 'red');
var xpos = $(this).width() / 2 + $(this).offset().left;
var ypos = $(this).height() / 2 + $(this).offset().top;
tip = createToolTip('thing', xpos, ypos);
$(this).parent().append(tip);
tip.offset({
left: tip.offset().left - tip.width() / 2
});
if (tip.offset().left < 0) tip.offset({
left: 0
});
if (tip.offset().left + tip.width() > $('body').width()) {
tip.offset({
left: $('body').width() - (tip.width())
});
}
}, function() {
$(this).css('color', '');
$(tip).remove();
});
function createToolTip(text, x, y) {
return $('<div />').addClass('toolTip').css('left', x).css('top', y).text(text);
}​
It's not perfect code, nor is it the same idea as you have for the tool tips, but hopefully it answers the question about keeping the items on screen.

Categories