Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Set style of each element in jquery

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!