Last active
February 4, 2020 16:42
-
-
Save hsnyc/8c4e0a4c92069efbf4b61b26b5139c8f to your computer and use it in GitHub Desktop.
A small script to make an element stick as you scroll vertically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.sticky { | |
position: fixed; | |
top: 40px; | |
background-color: #f7f8f9; | |
padding: 20px; | |
} | |
/* You can add a transition to the #div-to-make-sticky element to make the change smooth, for example */ | |
#div-to-make-sticky { | |
transition: padding 300ms ease-in; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Using Delay function in Wordpress to give time to php to load sidebar div element. | |
Remove setTimeout if you dont need to delay the script. | |
You can add/subtract to the offsetTop to fit your desire starting scroll position. | |
*/ | |
setTimeout(function() { | |
// Get the widget | |
var widgetDiv = document.querySelector('#div-to-make-sticky'); | |
//only do this if the element exist on the page. | |
if (widgetDiv) { | |
// Get the top offset position of the widget | |
var sticky = widgetDiv.offsetTop; | |
// When the user scrolls the page, execute this Function | |
window.onscroll = function() { | |
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position | |
if (window.pageYOffset > sticky) { | |
widgetDiv.classList.add("sticky"); | |
} else { | |
widgetDiv.classList.remove("sticky"); | |
} | |
}; | |
} | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment