How to move div up and down on a window scroll

I have a jquery function to move some div up and down, and the page scroll here is the code →

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

This code above only works on one div, for example →

<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>
Run codeHide result
+4
source share
2 answers

Instead of fields you should use "position: absolute" and "top" and "left". Using fields, you push them away from each other, making them massive.

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

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

+5
source

Weaving: http://kodeweave.sourceforge.net/editor/#3bc95f551a4e9cf7c52418361b4be806

. .mydiv #scroll.

CSS. , JS.

$(window).scroll(function() {
  $("#scroll").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});
body {
  height: 1176px;
  padding: 1em;
  font-size: 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv" id="scroll">This div works</div>
<div class="mydiv" id="scroll">This div takes a high distance from above div and goes down</div>
Hide result
0

All Articles