Skip to content

Instantly share code, notes, and snippets.

@lutsen
Last active December 27, 2015 09:09
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 lutsen/7302081 to your computer and use it in GitHub Desktop.
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.
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+'">&nbsp</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');
});
});
.element-container {
position: relative;
height: 100px;
}
.element {
width: 100%;
height: 100px;
z-index: 1;
}
<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