azhpo
azhpo

Reputation: 135

JQuery fadeTo()

I got this code so far:

$(window).scroll(function() {
    if ($(this).scrollTop() > 400) {
        $( ".top-bg" ).fadeTo("slow", 0.99);
    } 

The idea is a menu with low opacity and when I scroll down, it fades in but the problem is that I can't bring it back to low opacity (0.7) when I scroll back up to <400.

I have been searching around and I didn't find my solution.

Any idea?

Thanks in advance.

Upvotes: 0

Views: 116

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

A couple of issues there. First, you never check for scrollTop being <= 400, so of course it's not going to go back.

The second is that even with the code you have, you're constantly re-applying the fadeTo, any time the window scrolls, even if it was already > 400.

var fadedIn = false;
$(window).scroll(function() {
    var thisScroll = $(this).scrollTop();
    if (thisScroll > 400 && !fadedIn) {
        $( ".top-bg" ).fadeTo("slow", 0.99);
        // Or with a stop: $( ".top-bg" ).stop().fadeTo("slow", 0.99);
        fadedIn = true;
    } else if (thisScroll <= 400 && fadedIn) {
        $( ".top-bg" ).fadeTo("slow", 0.7);
        // Or with a stop: $( ".top-bg" ).stop().fadeTo("slow", 0.7);
        fadedIn = false;
    }
});

Upvotes: 1

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Try like this

$(window).scroll(function() {
    if ($(this).scrollTop() > 400) {
        $( ".top-bg" ).fadeTo("slow", 0.99);
    }else if($(this).scrollTop() <= 400)
{
        $( ".top-bg" ).fadeTo("slow", 0.7);
}

Upvotes: 0

Related Questions