Javascript sticky div after scrolling

This question may be silly for many here. I make a sticky div after the scroll in pure JS. Some people may advise doing this in jQuery, but I'm not interested in that. I need something similar to this . Here the div moves all the way to the top, but I need it to have a 60px top. I made a script, but it does not work. Can someone help me solve this problem?

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 is what I need to achieve. The left div should have margin-top:200px and position:absolute when loading the page. When the user scrolls the page, the left div should scroll and when it reaches top:60px; , its position and the top border of the edge should change to position:fixed and margin-top:60px;

Here is FIDDLE

+6
source share
1 answer

CSS

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

the stick class has been added, so javascript should not 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

+14
source

Source: https://habr.com/ru/post/950406/


All Articles