Reputation: 3792
I have a fixed div moving along my document as I scroll up/down. I am looking for the means to animate this div as soon as I reach the top of a specific div on my document. The animation will be very simple css, consisting of changing its background color to another color; if and only if I scroll to the top of the specific div.
For a more practical reference: if I am above div A, my fixed div (div B)'s background color will be blue; once I scroll to the top of A, B's background color will be red. If I scroll to the top of A again, the background color of the fixed div will change to blue... and so on.
My jQuery code:
(function($){
$(document).ready(function() {
var swapColors = 1; // used to swap colors on the #fixedDiv
$(window).scroll(function () {
if(swapColors) {
--swapColors;
if ($(window).scrollTop >= $('#landmarkDiv').offset().top) {
$('#fixedDiv').animate(
{
"background-color": "red"
}, "slow"
);
}
}
else {
++swapColors;
if ($(window).scrollTop < $('#landmarkDiv').offset().top) {
$('#fixedDiv').animate(
{
"background-color": "blue"
}, "slow"
);
}
}
}
}
})(jQuery);
Upvotes: 0
Views: 779
Reputation: 565
There's just many issues in your code.
You have an extra curly brackets in there. function(query) not required. works without it.
$(window).scrollTop needs a () at the end.
$(window).scrollTop();
.animate() function on a backgroundcolor has issues. You may need extra library to let jquery to do animation on color. Instead we can use css() and webkit-transition.
HTML:
</div>
<div id="testDiv">
Test div
</div>
<div id="landmarkDiv">
landmark
</div>
CSS:
#fixedDiv {
position: fixed;
top:0px;
width: 100%;
height:50px;
background-color: #456456;
-webkit-transition: all 3s;
}
#testDiv {
width: 600px;
height: 1200px;
}
#landmarkDiv {
width: 100%;
height: 1000px;
}
JQuery:
$(document).ready(function() { var swapColors = 1; // used to swap colors on the #fixedDiv
$(window).scroll(function () {
var windowScrollPosition = $(window).scrollTop();
if(swapColors) {
--swapColors;
if (windowScrollPosition >= $('#landmarkDiv').offset().top) {
$('#fixedDiv').css('backgroundColor', "red");
console.log(windowScrollPosition, 'more');
}
}
else {
++swapColors;
if (windowScrollPosition < $('#landmarkDiv').offset().top) {
$('#fixedDiv').css('backgroundColor', "blue");
console.log(windowScrollPosition, 'less');
}
}
});
});
Working test here: www.gdiction.com/scroll
Upvotes: 1