I have 3 logo image (#logo, #logo2, #logo3) that move randomly around the page with my javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2 /jquery.min.js"></script>
<script type="text/javascript">
function moveDiv() {
var $span = $("#logo");
$span.fadeOut(500, function() {
var maxLeft = $(window).width() - $span.width();
var maxTop = $(window).height() - $span.height();
var leftPos = Math.floor(Math.random() * (maxLeft + 10))
var topPos = Math.floor(Math.random() * (maxTop + 10))
$span.css({ left: leftPos, top: topPos }).fadeIn(2500);
});
};
moveDiv();
setInterval(moveDiv, 2500);
</script>
My problem is that all of them start at the same position in the page (on top left corner) overlapping by themselves, only for the duration of the first fadeout. How can I let them start in a random position around the page since the first click on my webpage?
Thanks,
Michele
There are few moments that are important here:
top
andleft
coordinates initially so they don't flash from the same position.src
attribute directly on the DOM object.position: fixed;
as it positions relative to the viewport and don't move elements as page is scrolled.setInterval
call becausefadeIn/fadeOut
already have timers inside.Here is the demo:
Give them all the same class e.g
logo
and select them using this class :Or use start with
^
selector :And use
each()
to move them all, and you should set the position toabsolute
so theleft/top
rules can take effect :Hope this helps.
Set your logos' positions on some random values in the
onload
event, for example: