Reputation: 5454
I'm trying to change the Opacity
of an element when I scroll down. and change the opacity back to its normal state when I scroll back to the top. But I'm having problems doing this.
#menu
{
opacity:0.6
}
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$( "#menu" ).fadeTo("fast", 1);
} else {
$( "#menu" ).fadeTo("fast", 0.6);
}
});
The above code doesn't work or in some cases it works after a bit and stops again! I'm really confused cause I tried the code below to simply fade it and it works without a hitch.
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$( "#menu" ).fadeOut();
} else {
$( "#menu" ).fadeIn();
}
});
Upvotes: 1
Views: 414
Reputation: 3369
To make it short, you could do it like this:
var _st;
$(window).scroll(function ()
{
_st = $(this).scrollTop();
$('#menu').css({opacity:(_st > 100) ? 0 : 1 });
})
#menu { transition: opacity 0.5s linear 0s; }
Upvotes: 1
Reputation: 6263
First of all, I recommend to use .stop()
before fadeTo
method, as you are executing it on every scroll
event!
After that, your two code blocks are not the same, in the first one, you are showing element (opacity 1) if scroll is greater than 100, the second code is vice versa, try this:
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$( "#menu" ).stop().fadeTo("fast", 0.6);
} else {
$( "#menu" ).stop().fadeTo("fast", 1);
}
});
Upvotes: 1
Reputation: 315
I would do this:
$(window).scroll(function ()
{
if (window.pageYOffset > 100)
{
$('#menu').addClass('no-opacity');
}
else
{
$('#menu').removeClass('no-opacity');
}
});
in css:
.no-opacity { opacity:0; }
in css again: make the change happen gradually:
#menu { transition: all 0.5s linear 0s; }
Upvotes: 1