15

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
rubixibuc
  • 7,111
  • 18
  • 59
  • 98

1 Answers1

18
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
}
Eric Gumba
  • 435
  • 3
  • 16
Jake
  • 2,471
  • 15
  • 24
  • 2
    You're awesome:-) that worked perfectly in every browser I tried it in. Thank you so much for helping me. – rubixibuc Apr 11 '11 at 04:29
  • @Jake First of all it has to be your_div.style.top (style is missing in your code) isn`t? And also this moves a div only once and not as we scroll. Please correct me if I`m wrong! – Ashwin Nov 16 '15 at 09:04
  • This code seems to work great, I'm curious though, why no curly brackets? – teewuane Sep 11 '17 at 15:38