Sonnie Thomas Sonnie Thomas - 1 year ago 62
CSS Question

How can I make this background become less opaque as the page scrolls down?

I'm new to JQuery literally all I can do is make a div fade in and out if something is clicked and the JQuery you're about to see below. Anyways I was just wondering if someone could help me make this background less opaque as the screen scrolls down. So far I've managed to make it so that when the screen is 50px or more down then the background appears but I would like to be able to make it slowly become less opaque (slowly appear). Thanks for your help! :P

People are saying there's a question the same as mine, it's similar but not the same here's why:

I need the css selector "rgba(0, 0, 0, 0.0)" the last value needs to slowly increase and make it's way to 1 (Example here: "rgba(0, 0, 0, 1" ) as the page scrolls down. THIS IS NOTHNG TO DO WITH OPACITY


$(document).ready(function() {

$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 100) {
$(".top-nav-container").css({"background-color": "rgba(0, 0, 0, 0.1"});
} else {
$(".top-nav-container").css({"background-color": "rgba(0, 0, 0, 0.0"});

Answer Source

Calculate opacity based on the quotient of the scroll top height and the window height:

$(document).scroll(function() {

    var wh = $(window).height();
    var y = $(this).scrollTop();

    var thisOpacity = 1 - (y / wh);    

    $(".top-nav-container").css({"background-color": "rgba(0, 0, 0, " + thisOpacity + ")"});

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download