Reputation: 585
Does anyone know how I can achieve the following with jQuery:
I want to add a class (.fixed) to an element (#content) when a user reaches 50px above #content. And then, when the user scrolls up 50px above #content, I want to remove the class.
How can I do this with as little script as possible?
<div id="header">
</div>
<div id="content">
</div>
<div id="content-2">
</div>
Upvotes: 2
Views: 24421
Reputation: 181
If I understand correctly, this should do the trick.
$(function(){
$(document).scroll(function(){
if($(this).scrollTop() >= $('#content').offset().top - 50) {
$("#content").css("background","red");
} else {
$("#content").css("background","orange");
}
});
});
Basically, it check the current position of the user's scroll and compare it to the position of the div minus 50 pixel.
If you just past this code in your document, it should work properly.
Upvotes: 7
Reputation: 974
Try this,
$(window).scroll(function() {
if ($(this).scrollTop() > 50){
$('#content').addClass("content_fixed");
}
else{
$('#content').removeClass("content_fixed");
}
});
Demo : http://jsfiddle.net/UI_Designer/8j0a1Lkk/1/
Upvotes: 3
Reputation: 151
You can use the jquery plugin waypoint (http://imakewebthings.com/waypoints/) to detect when the user has scrolled to the area and then use the javascript .innerhtml function to change the html code. The one problem with this method is that you have to have another element that surrounds your main element ONLY.
Upvotes: 1