Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  67] [ 1]  / answers: 1 / hits: 39930  / 11 Years ago, sat, july 27, 2013, 12:00:00

This question maybe stupid for many here. I am making sticky div after scroll in pure JS. Some people may advice to make it in jQuery but i am not interested in it. What i need is something similar to this. Here the div moves all the way to top but i need it to have 60px top. I made a script but it not working. Can anyone help me solve this?



Here is my code.



HTML



<div id=left></div>
<div id=right></div>


CSS



#left{
float:left;
width:100px;
height:200px;
background:yellow;
}

#right{
float:right;
width:100px;
height:1000px;
background:red;
margin-top:200px;
}


JS



window.onscroll = function()
{
var left = document.getElementById(left);



if (left.scrollTop < 60 || self.pageYOffset < 60) {
left.style.position = 'fixed';
left.style.top = '60px';
} else if (left.scrollTop > 60 || self.pageYOffset > 60) {
left.style.position = 'absolute';
left.style.margin-top = '200px';
}

}


This what i need to achieve. The left div has to have margin-top:200px and position:absolute on page load. When the user scrolls the page, the left div should scroll and when it reaches top:60px; its position and margin-top should change to position:fixed and margin-top:60px;



Here is the FIDDLE


More From » scroll

 Answers
72

CSS



#left {
float:left;
width:100px;
height:200px;
background:yellow;
margin:200px 0 0;
}
#left.stick {
position:fixed;
top:0;
margin:60px 0 0
}


added a stick class, so javascript doesn't have to do too much work.



JS



    // set everything outside the onscroll event (less work per scroll)
var left = document.getElementById(left),
// -60 so it won't be jumpy
stop = left.offsetTop - 60,
docBody = document.documentElement || document.body.parentNode || document.body,
hasOffset = window.pageYOffset !== undefined,
scrollTop;

window.onscroll = function (e) {
// cross-browser compatible scrollTop.
scrollTop = hasOffset ? window.pageYOffset : docBody.scrollTop;

// if user scrolls to 60px from the top of the left div
if (scrollTop >= stop) {
// stick the div
left.className = 'stick';
} else {
// release the div
left.className = '';
}
}


WORKING JSFIDDLE


[#76708] Friday, July 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eddiejoshb

Total Points: 659
Total Questions: 105
Total Answers: 100

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;