Edd Neal
Edd Neal

Reputation: 3

JQuery Scroll controls opacity of a Nav to fade in, how to stop Nav fading out on reverse scroll?

I am in need of help with some jquery. I have a fixed nav at the top of the page thats opacity is set to 0 on page load. When the page is scrolled down the nav fades in using:

function EasyPeasyParallax() {
    scrollPos = $(this).scrollTop();
$('#nav').css({
        'opacity': 0+(scrollPos/800)
    });
});

How can I make it so when the page is scrolled back up it doesn't fade back out?

I have tried doing this with an if statement but my jquery isn't too hot.

Thanks in advance. Edd Neal.

Upvotes: 0

Views: 1165

Answers (2)

Adrian Trainor
Adrian Trainor

Reputation: 257

Try this:

$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 200){
             $('#nav').fadeIn(1000);   
        }
    });
});

With the css:

#nav{
    display:none;
    position:fixed;
    top:0px;
    left:0px;
    width:100%;
    height:50px;
    background-color:red;
}

A working JSFiddle can be found here.

Using the fadeIn() is better than manually changing css because jquery takes care of cross browser css issues automatically. For example, the opacity for IE is alpha(opacity=50)

Upvotes: 1

Yotam Omer
Yotam Omer

Reputation: 15376

Use this: (woking jsFiddle)

function EasyPeasyParallax() {
    scrollPos = $(document).scrollTop();
        $('#nav').css({
            'opacity': 0+(Math.min(scrollPos/800,1))
        });
};

$(function(){
    $('body').bind('mousewheel',EasyPeasyParallax);
});

Note: I've used mousewheel event however you can detect the scroll in any way you'd like. also note Math.min() usage so the value of opacity will not exceed 1

Another note: use .stop().animate() instead of .css() for a nicer looking fade effect jsFiddle.

Upvotes: 3

Related Questions