I have a page on which the menu background-color is XYZ on the front page. On any subsequent (due to the nav background changing on sub-pages) page the NAV background color changes so that I will also have to change the background-color for the nav items themselves. Here is an example:
.nav__menu {
ul {
display: flex;
li {
padding: 3px;
&:hover {
background-color: rgba(0, 0, 0, 0.3);
}
}
}
}
So far, so good. This SCSS will set the standard background-color for the front page. Once switching to other sites, I have opted to change the color dynamically via JS:
$(document).ready(() => {
const path = window.location.pathname;
const root_path = path.substring(path.lastIndexOf("/"));
if (path !== root_path) {
$(".nav__menu ul li a").css("color", "#0c9594");
$(".nav__menu ul li").hover(
e => {
const el = $(e.target);
if (el[0].nodeName == "LI") {
$(el).css("background-color", "rgba(0, 0, 0, 0.1)");
}
},
e => {
const el = $(e.target);
if (el[0].nodeName == "LI") {
$(el).css("background-color", "transparent");
}
}
);
} else {
$(".nav__menu ul li a").css("color", "#f9f6ef");
}
Within the jQuery hover
method I have to specify e.target
because this
refers to the window object. Also, since the LI has an anchor tag inside of it, I have to check that the CSS are applied to the right elements by using [0]
.
This behavior is extremely faulty, in that it sometimes doesn't remove the applied background-color.
Please help me make this work as intended, hover in applying the color, hover out removing it.
Here is a CodePen