Nav Issues (this is JS and CSS but mostly JS, I think)

Nav Issues (this is JS and CSS but mostly JS, I think)
0.0 0

#1

I’ve been working on my portfolio… I feel inspired recently seeing everyone work so hard.

One thing that I’ve programmed in is some behavior of my nav bar. Here’s what I want it to do:

  • by default it is not visible. This is set in CSS opacity: 0;
  • when the user scrolls down and the distance scrolled is greater than 150, the nav bar will fade in. This is determined in JS, and the css opacity property is set to 1
  • when the user scrolls up the page back to the top and we get less than 150 distance from the top, the nav bar will hide. Also determined in JS, and css opacity set to 0.

The Bug:
The behavior I expect is that the the user could still hover over the nav bar even when it is hidden. This is how it is in default, however, after the JQuery fires and sets the opacity based on scroll, the hover behavior from css doesn’t work.

What I want to fix:
Anytime the user hovers over the nav bar, I want it to become visible if it is hidden. By default it works, after scrolling down and up again it does not.

I feel like I need some fresh eyes on the issue. I’m a little tired, too… doesn’t help. Would appreciate any help!

What I’ve tried that didn’t work:

  • event listener in JS for hover.
  • add and remove classes with Jquery rather than set opacity

The Code:
I’ve isolated the issue in this codepen: https://codepen.io/dcookwebdev/pen/aGVVwm


#2

Well I seemed to have found a workaround by adding this code:

let navbarHidden = true;
let pageScrolledDown = false;

let navbar = document.getElementById("navbar");
navbar.addEventListener("mouseover", function() {
  if (!pageScrolledDown) {
    navbar.style.opacity = "1";
    navbarHidden = false;
  }
})

navbar.addEventListener("mouseout", function() {
  if (!pageScrolledDown) {
    navbar.style.opacity = "0";
    navbarHidden = true;
  } 
})

(during scrolling up/down it will set the pageScrolledDown to true or false)

It works… but I don’t know exactly why the issue was there in the first place. Also, I feel as though I shouldn’t really need this work around. So, my workaround may be unnecessary. If anyone has any thoughts please let me know. Thanks!


#3

I found a topic that’s similar on stack overflow: https://stackoverflow.com/questions/30991861/retain-css-hover-when-changing-css-styles-with-javascript

Instead of setting the navbar opacity to 0, setting it to nothing makes it work>> $(".navbar")("opacity", ""). It seems that setting things in JS will take over and override CSS. So I found out the why which is good! Good to know. My above work around is not necessary, even though it worked!