Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to move div up & down on window scroll

I have a jquery function to move some div up and down while scrolling the page here is the code ->

$(window).scroll(function() {
  $(".mydiv").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});

This above code only works on one div like ->

<div class="mydiv">This div works</div>
<div class="mydiv">This div takes a high distance from above div and goes down</div>

$(window).scroll(function() {
  $(".mydiv").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});
body {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv">This div works</div>
<div class="mydiv">This div takes a high distance from above div and goes down</div>
like image 352
Aniket Singh Avatar asked Apr 23 '16 11:04

Aniket Singh


1 Answers

You should be using 'position: absolute' and 'top' and 'left' instead of margins. By using margins you are pushing them off each other making them make the page massive.

$(window).scroll(function() {
  $(".mydiv").css({
    "top": ($(window).scrollTop()) + "px",
    "left": ($(window).scrollLeft()) + "px"
  });
});

See this codepen - http://codepen.io/dmoojunk/pen/JXBaXm

like image 77
dmoo Avatar answered Sep 20 '22 10:09

dmoo