You will need to use Javascript to check the position of your element ("myElement") on the page compared to how far the page scrolls. If the page has been scrolled above your element, you modify your css element to snap it to the top of the page. Note: mobile browsers do not like "position: fixed"; style.
Give the element the identifier "myElement" and paste it into your tag.
<script type="text/javascript"> var yPosition; // save original y position of element here window.onload = function(){ // once entire page is loaded this function is fired // save original y position of element before it is scrolled yPosition = document.getElementById("myElement").offsetTop; } window.onscroll = function(){ // scrolling fires this function var myElement = document.getElementById("myElement"); // for cleaner code // compare original y position of element to y position of page if( yPosition <= window.pageYOffset ){ // snap element to the top by changing css values of element myElement.style.position = "fixed"; myElement.style.top = "0px"; }else{ // re-position to original flow of content myElement.style.position = "relative"; myElement.style.top = ""; // set to default } } </script>
Hope this helps!
source share