Jeremy
Jeremy

Reputation: 25

JavaScript-CSS : Trouble getting Nav Menu to change from transparent to opaque on scroll

Okay, so I'm playing around with some design ideas and can't seem to get the JavaScript to do what I want it to. I want a transparent TopNav, that when the user scrolls to say 48px or wherever I deem the TopNav background goes black. Crude Example below of what I want to happen, but when i scroll the TopNav just stays transparent. I've tried a couple of solutions from other answers here to the point of copy/paste and just edit the element names to match my html. I'm just not sure what I'm doing wrong:
Start

Scroll


CSS

body {
    font-family: Futura, Arial, Trebuchet MS, sans-serif;
}

header {
    margin: 0;
}
.stickyNav {
    position:fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 48px;
}
.topNav {
    max-width: 1366px;
    display: flex;
    justify-content: space-between;
    margin: 0 auto;
    background-color: black;
    color: #D4D4D4;
    height: 48px;
}
.scroll {
    background-color:#000000;
}
.navigationMenu{
    display: inline-flex;
    list-style: none;
}

JS
var myNav = document.getElementById("TopNav");

window.onscroll = function() {
  "use strict";
  if (document.body.scrollTop >= 1 || document.documentElement.scrollTop >= 1) {
    myNav.classList.add("scroll");
  } else {
    myNav.classList.remove("scroll");
  }
};

HTML
<header >
    <div class="stickyNav" >
        <nav class="topNav" id="TopNav">
            <h3>LOGO HERE</h3>
            <ul class="navigationMenu">
                <li class="navigationItem">Home</li>
                <li class="navigationItem">Services</li>
                <li class="navigationItem">About</li>
                <li class="navigationItem">Contact</li>
                </ul>
        </nav>
    </div>
</header>

Upvotes: 0

Views: 29

Answers (1)

Kevin
Kevin

Reputation: 72

can't seem to get the JavaScript to do what I want it to

This is a matter of CSS styling - not Javascript. The Javascript job in this code is just to detect scroll and add or remove the class.

So if you want the default background to be transparent do one of these:

.topNav { background-color: transparent; } // transparent
.topNav { background-color: rgba(0,0,0,0); } // transparent

and after adding a class to have a background, do:

.topNav.scroll { background-color: rgba(0,0,0,.5); }} // 50% black, "semi-transparent"

Upvotes: 1

Related Questions