Skip to content

Instantly share code, notes, and snippets.

@hsnyc
Last active February 4, 2020 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsnyc/8c4e0a4c92069efbf4b61b26b5139c8f to your computer and use it in GitHub Desktop.
Save hsnyc/8c4e0a4c92069efbf4b61b26b5139c8f to your computer and use it in GitHub Desktop.
A small script to make an element stick as you scroll vertically
.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;
}
/*
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