Reputation: 1097
I'm tryng to make a smooth transition on a background color menu with scroll function and animate(). But it's not working, although other properties like changing the width do work...For now I'm using the css method, bu the goal is a "fade in and out" effect...can someone tell me what is wrong? I've searched and others solutions don't work (even with hover functions...) The code:
JS:
$(window).scroll(function () {
var top = $(window).scrollTop();
if (top > 0) {
//this line works
$('.menu').css('opacity','0.7').css('background-color','#383737');
//but not this one:
$('.menu').animate({"background-color":"#383737"}, 1000);
}
})
CSS:
.menu{
top:0;
width: 100%;
font-size: 4vw;
text-align: center;
background-color: #ED1847;
z-index: 1;
color:black;
position:fixed;
}
Upvotes: 1
Views: 484
Reputation: 16575
A solution is css3
. you can use transition
to make background color smooth via addClass
and removeClass
to toggle css class with jquery.
$(window).scroll(function() {
var top = $(window).scrollTop();
if (top > 0) {
$('.menu').addClass('newColor');
} else {
$('.menu').removeClass('newColor');
}
});
If you want ,you can include jquery ui
library and make animate
work.
$(window).scroll(function() {
var top = $(window).scrollTop();
if (top > 0) {
$('.menu').stop(true, true).animate({
backgroundColor: '#ED1847'
})
} else {
$('.menu').stop(true, true).animate({
backgroundColor: '#383737'
})
}
});
Upvotes: 2
Reputation: 1861
Animate Properties and Values
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used).
$('.menu').animate({backgroundColor:"#383737"}, 1000);
Upvotes: 3