I have the following code to set the opacity of all elements not being hovered over to 0.5.
const handleHover = function (e) {
if ($(e.target).hasClass("nav_link")) {
const siblings = e.target.closest("nav").querySelectorAll(".nav_link");
siblings.forEach((el) => {
if (el !== e.target) el.style.opacity = this;
});
}
};
$(".nav").on("mouseover", handleHover.bind(0.5));
$(".nav").on("mouseout", handleHover.bind(1));
My question is how can I write the forEach loop on the siblings using a jQuery method rather than using querySelectorAll?
I wouldn't use JavaScript or jQuery at all for this.
Using CSS, you can target all the .nav_link elements that are within a nav being hovered but are themselves, not hovered.
.nav_link {
transition: opacity .1s;
cursor: pointer;
}
nav:hover .nav_link:not(:hover) {
opacity: .5;
}
<nav>
<ul>
<li class="nav_link">Link #1</li>
<li class="nav_link">Link #2</li>
<li class="nav_link">Link #3</li>
<li class="nav_link">Link #4</li>
</ul>
</nav>
For completeness, here's a jQuery version
// Delegated hover in / out event handler
$("nav").on("mouseenter mouseleave", ".nav_link", e => {
$(e.delegateTarget) // start at "<nav>"
.find(".nav_link") // find all the links
.not(e.target) // except the hovered one
.toggleClass("fade"); // toggle the "fade" class
});
.nav_link { cursor: pointer; transition: opacity .1s; }
.fade { opacity: .5; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script><nav><ul><li class="nav_link">Link #1</li><li class="nav_link">Link #2</li><li class="nav_link">Link #3</li><li class="nav_link">Link #4</li></ul></nav>