Home > Net >  How can I use for loop in jQuery hover
How can I use for loop in jQuery hover

Time:10-04

I want to use loops to iterate and apply hover with each element then remove class from another collection of elements. Tried each function but didn't work.

$("#product").hover(function () {
    $(".z").removeClass("viz");
    $(".arrow1").css("transform", "rotate(180deg)")
}, function () {
    $(".z").addClass("viz");
    $(".arrow1").css("transform", "rotate(0deg)")
})
$("#company").hover(function () {
    $(".y").removeClass("viz");
    $(".arrow2").css("transform", "rotate(180deg)")
}, function () {
    $(".y").addClass("viz");
    $(".arrow2").css("transform", "rotate(0deg)")
})
$("#connect").hover(function () {
    $(".x").removeClass("viz");
    $(".arrow3").css("transform", "rotate(180deg)")
}, function () {
    $(".x").addClass("viz");
    $(".arrow3").css("transform", "rotate(0deg)")
})

CodePudding user response:

You can create an array of the IDs of the elements you want to select and loop through them. like this:

let list = ['product', 'company', 'connect']
list.forEach(element => {
  $("#" element).hover(function () {
      $(".z").removeClass("viz");
      $(".arrow1").css("transform", "rotate(180deg)")
  }, function () {
      $(".z").addClass("viz");
      $(".arrow1").css("transform", "rotate(0deg)")
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

EDIT: Using jquery selectors, for selecting list items of a ul with id="menu" is something like this:

var items = $("ul#menu li");
for (let li of items) {
    $(li).hover(function () {
        // ...
    })
}
  • Related