tomcwatts
tomcwatts

Reputation: 1

Javascript on scroll to change nav bar opacity is making my nav content dissapear

I've looked everywhere but I can't find an answer that applies to this problem.

I have a sticky nav bar that becomes opaque upon scrolling, using this code:

    var target = $('#navbar-container');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('opacity', 1);
    }
    else  target.css('opacity', 0.50);
});

But this code makes the background, and everything within the nav bar opaque, and I want the text links, and a logo to remain visible. I've read about using an RGB background to make only the background opaque, but I'm unsure how to do this within this code's parameters. I'm sure there's a simple solution, but I can't find it!

Upvotes: 0

Views: 1451

Answers (2)

James Martin-Davies
James Martin-Davies

Reputation: 651

This is because the parent container will affect any children when using opacity.

Use rgba.

CSS

#navbar-container {
    background-color: rgba(255, 255, 255, 1);
}

JS

var target = $('#navbar-container');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('background-color', 'rgba(255, 255, 255, 1)');
    }
    else  target.css('background-color', 'rgba(255, 255, 255, 0.5)');
});

Upvotes: 2

hotforfeature
hotforfeature

Reputation: 2588

Use the background-color attribute instead of opacity.

target.css('background-color', 'rgba(0, 0, 0, 0.5)');

rgba(red, green, blue, alpha)

Upvotes: 2

Related Questions