Created
February 7, 2011 17:29
-
-
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.
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
// @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'); | |
} | |
}); | |
}); |
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
// @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