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>
FIDDLE
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>
FIDDLE
Share Improve this question edited Mar 5, 2015 at 3:35 caustic asked Mar 5, 2015 at 3:27 causticcaustic 5852 gold badges8 silver badges18 bronze badges 1- can you clarify? you want to add a class when they are 50px above content, then remove the class when they are...50 px above content? I don't quite undertand – chiliNUT Commented Mar 5, 2015 at 3:53
3 Answers
Reset to default 7If 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 pare it to the position of the div minus 50 pixel.
If you just past this code in your document, it should work properly.
Try this,
$(window).scroll(function() {
if ($(this).scrollTop() > 50){
$('#content').addClass("content_fixed");
}
else{
$('#content').removeClass("content_fixed");
}
});
Demo : http://jsfiddle/UI_Designer/8j0a1Lkk/1/
You can use the jquery plugin waypoint (http://imakewebthings./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.