Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Created February 7, 2011 17:29
Show Gist options
  • Save johanbrook/814776 to your computer and use it in GitHub Desktop.
Save johanbrook/814776 to your computer and use it in GitHub Desktop.
Two snippets for making an element fixed after scrolling over a certain point. Saving for reference.
// @rem's solution
$(document).ready(function () {
var $comment = $('#comment'),
top = $comment.offset().top - parseFloat($comment.css('marginTop').replace(/auto/, 0)),
$window = $(window);
$window.scroll(function (event) {
// what the y position of the scroll is
var y = $window.scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$comment.addClass('fixed');
} else {
// otherwise remove it
$comment.removeClass('fixed');
}
});
});
// @octavioamu's solution
var fixed = false;
$(document).scroll(function() {
if( $(this).scrollTop() >= 100 ) {
if( !fixed ) {
fixed = true;
$('#myDiv').css({position:'fixed',top:20});
}
} else {
if( fixed ) {
fixed = false;
$('#myDiv').css({position:'static'});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment