Search code examples
javascriptclasswebflow

Checking a number in a class and adding a class to it


I am new to coding and so I don't really what I am looking for. The problem is that I want to add a class to an existing class when hovering in and when I'm hovering out it should remove the class. Now I have three combo classes as you can see (.image-1, .image-2, .image-3) and I want to add the class "isplaying" to all of them individually because they have different content.

For now, I just duplicated the functions but do you know a more elegant or simpler way?

(I tried to use an if-statement to check the number in the string but it didn't work).

Thanks in advance!

<script>
$(".category.image-1").hover(
  function () {
    $(this).addClass("isplaying");
  },
  function () {
    $(this).removeClass("isplaying");
  }
);
$(".category.image-2").hover(
  function () {
    $(this).addClass("isplaying");
  },
  function () {
    $(this).removeClass("isplaying");
  }
);
$(".category.image-3").hover(
  function () {
    $(this).addClass("isplaying");
  },
  function () {
    $(this).removeClass("isplaying");
  }
);
</script>

Solution

  • You can use the class in your selector to match the image- classes:

    $(".category[class*='image-']").hover(
      function () {
        $(this).addClass("isplaying");
      },
      function () {
        $(this).removeClass("isplaying");
      }
    );
    

    This will give you the elements that have the classes category and the class attribute also contains the following image-. This will match with all 3 (and any additional) of your elements.