I'm working on a project that is a series of posts on a page, and when the browser scrolls over, classes are added to that post only. I have a working concept here: http://jsfiddle.net/chdhmphry/V7jPU/
My issue is that this highlights all of the posts instead of just one. I tried to do a few work arounds, but non seem to allow me to just add the class to the post that fits the perameters(within 20px of the top of the window). I tried $(this)
, hence why $(".post").ready(function () {
is a part of the code. What exactly am I doing wrong?
The jQuery:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
$(".post").ready(function () {
post = $(".post", this).offset().top,
opacity = post - 20;
if (scroll >= opacity) {
$(this).addClass("seventy");
} else{
$(this).removeClass("seventy");
}
});
});
I changed it to each post, and changed how you got the value for post. This has been edited to address your question in the comment: When the bottom of the post goes below the scrollTop then it will lose the seventy class.
$(".post").each(function () {
var postTop = $(this).offset().top - 20,
postBottom = $(this).height() + postTop - 100; // -100 is just to show it work, remove.
if (scroll >= postTop &&
scroll <= postBottom) {
$(this).addClass("seventy");
} else{
$(this).removeClass("seventy");
return false; // more efficient, but might not work.
}
});