Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move a div on scroll?

I have to move a div when the the user scrolls, but need to use pure JavaScript.

position: fixed; will not work with the layout. The div's original position is relative to something else. Is there a simple implementation using an event like onscroll, to detect how many pixels the page moved up or down, and change the position of the div accordingly?

The div only needs to move vertically. So if I can detect how many pixels the page has moved I can just add or subtract that to the location of the div.

like image 811
rubixibuc Avatar asked Apr 11 '11 02:04

rubixibuc


People also ask

How do I move a div while scrolling?

Just add position: fixed; in your div style. I have checked and Its working fine in my code. position: fixed isn't enough when you want your div to move only along with one of the scrolls, X or Y. The accepted answer is perfect.

How do I scroll to a specific div in HTML?

If you want to scroll the current document to a particular place, the value of HREF should be the name of the anchor to which to scroll, preceded by the # sign. If you want to open another document at an anchor, give the URL for the document, followed by #, followed by the name of the anchor.


1 Answers

window.onscroll = function (e) {
  var vertical_position = 0;
  if (pageYOffset)//usual
    vertical_position = pageYOffset;
  else if (document.documentElement.clientHeight)//ie
    vertical_position = document.documentElement.scrollTop;
  else if (document.body)//ie quirks
    vertical_position = document.body.scrollTop;

  var your_div = document.getElementById('some_div');
  your_div.style.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}
like image 52
Jake Avatar answered Oct 07 '22 13:10

Jake