Search code examples
jquerymouseentermouseleave

How can I simplify my Jquery code while keeping addClass and removeClass?


Every time I add a new <li> and <img> element I also have to add a new line of code in the .js file

Codepen Here is the online code of how it works and how it should continue to work after editing the script.

//Mouseenter
  $(".list li:nth-child(1)").on('mouseenter', function() {
    $(".img-display img.show").removeClass("show");
    $(".img-display img:nth-child(1)").addClass("show");
  })

  $(".list li:nth-child(2)").on('mouseenter', function() {
    $(".img-display img.show").removeClass("show");
    $(".img-display img:nth-child(2)").addClass("show");
  })

  $(".list li:nth-child(3)").on('mouseenter', function() {
    $(".img-display img.show").removeClass("show");
    $(".img-display img:nth-child(3)").addClass("show");
  })

//Mouseleave
  $(".list li:nth-child(1)").on('mouseleave', function() {
    $(".img-display img.show").addClass("show");
    $(".img-display img:nth-child(1)").removeClass("show");
  })

  $(".list li:nth-child(2)").on('mouseleave', function() {
    $(".img-display img.show").addClass("show");
    $(".img-display img:nth-child(2)").removeClass("show");
  })

  $(".list li:nth-child(3)").on('mouseleave', function() {
    $(".img-display img.show").addClass("show");
    $(".img-display img:nth-child(3)").removeClass("show");
  })

I wanted to be able to simplify my code by keeping addClass, removeClass, mouseenter & mouseleave and not having to add another line of code every time I add new elements.

At the moment I only have this to identify the elements of the list:

  $(".list li").on('mouseenter', function() {
    var index = $(this).index()
  })

Solution

  • Anyway you just need a little reasoning for this problem. Here's all you need:

      const lis = $(".list li")
      lis.on('mouseenter', function() {
        const index = lis.index(this)
        
        $(".img-display img.show").removeClass("show");
        $(".img-display img").eq(index).addClass("show")
      })