Last active
December 27, 2015 09:09
-
-
Save lutsen/7302081 to your computer and use it in GitHub Desktop.
Stick a menu (or other element) to the top of the page when scrolling past it, using jQuery.
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
var element_start_offset = 0; | |
var element_sticks = false; | |
function stickToTop(element) { | |
// You may need to insert a placeholder to prevent other content from "jumping" | |
// Make sure it has the same height as "element" | |
placeholder = element.substr(1)+'_placeholder'; | |
if ($(document).scrollTop() >= element_start_offset.top && !element_sticks) { | |
$('<div id="'+placeholder+'"> </div>').insertAfter(element); // Insert placeholder | |
$(element).css({ | |
'position':'fixed', | |
'top':'0', | |
'right':'0', | |
'left':'0' | |
}); | |
element_sticks = true; | |
} else if ($(document).scrollTop() < element_start_offset.top && element_sticks) { | |
$('#'+placeholder).remove(); // Remove placeholder | |
$(element).css({ | |
'position':'relative' | |
}); | |
element_sticks = false; | |
} | |
} | |
$(function (){ | |
element_start_offset = $('#element').offset(); | |
// Keep menu on top of window when scrolling | |
$(document).scroll(function() { | |
stickToTop('#element'); | |
}); | |
}); |
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
.element-container { | |
position: relative; | |
height: 100px; | |
} | |
.element { | |
width: 100%; | |
height: 100px; | |
z-index: 1; | |
} |
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
<link rel="stylesheet" type="text/css" media="all" href="ꞈexample.css" /> | |
<p>Content before</p> | |
<!-- element-container is needed to keep height of total page the same after element is "removed" and prevent ugly jumping of page --> | |
<div class="element-container"> | |
<div class="element" id="element"> | |
Element content | |
</div> | |
</div> | |
<p>Content after</p> | |
<script src="http://code.jquery.com/jquery-latest.js"></script> | |
<script src="stick_to_top.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment