Sunday, May 19, 2024
110
rated 0 times [  115] [ 5]  / answers: 1 / hits: 30312  / 13 Years ago, mon, april 11, 2011, 12:00:00

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.


More From » vertical-scrolling

 Answers
92
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
}

[#92822] Friday, April 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;