Michele de Candia Michele de Candia - 13 days ago 13
Javascript Question

Javascript object starting with random position

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

Answer

Give them all the same class e.g logo and select them using this class :

var $spans = $(".logo");

Or use start with ^ selector :

var $spans = $("[id^='logo']");

And use each() to move them all, and you should set the position to absolute so the left/top rules can take effect :

div{
    position: absolute;
}

Hope this helps.

function moveDiv() {
  var $spans = $(".logo");

  $spans.each(function(){
    var _this = $(this);

    _this.fadeOut(500, function() {
      var maxLeft = $(window).width() - _this.width();
      var maxTop = $(window).height() - _this.height();
      var leftPos = Math.floor(Math.random() * (maxLeft + 10))
      var topPos = Math.floor(Math.random() * (maxTop + 10))

      _this.css({ left: leftPos, top: topPos }).fadeIn(100); 
      console.log(leftPos,topPos);
    });
  });
};

moveDiv();
setInterval(moveDiv, 1000);
div{
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo" id="logo" > LOGO</div>
<div class="logo" id="logo1" > LOGO 1</div>
<div class="logo" id="logo2" > LOGO 2</div>
<div class="logo" id="logo3" > LOGO 3</div>