Last active
September 29, 2016 18:55
-
-
Save treykane/13a1eb1602f755cb791dda5062beec2e to your computer and use it in GitHub Desktop.
JQuery - Sticky Element on scroll when it reaches the top of the browser window
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
.is-sticky { | |
position: fixed; /* why it sticks */ | |
top: 0; /* can be adjusted as needed */ | |
margin: 0; | |
z-index: 999; /* be on top of all the things */ | |
}/* is-sticky */ |
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
// creating navigation that sticks to the top of the browser when you scroll to it. | |
$(document).ready(function() { | |
var stickyElement = '.your-element-here'; // What element would you like to target? | |
var stickyNavTop = $(stickyElement).offset().top; // get the offset of our element from the top of the browser | |
var stickyNav = function(){ // when we scroll watch for the element to reach the top of the browser and for the element to drop below the top of the browser | |
var scrollTop = $(window).scrollTop(); | |
if (scrollTop > stickyNavTop) { | |
$(stickyElement).addClass('is-sticky'); // add class so element sticks | |
} else { | |
$(stickyElement).removeClass('is-sticky'); // remove class so element unsticks | |
} | |
}; | |
stickyNav(); | |
$(window).scroll(function() { | |
stickyNav(); // run all of the things | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment