Change class on current elemet only (jQuery+this)

Viewed 39

I need to change class on hover only for current element, probably with 'this'. Here is working code but it changes classes for all elements.

https://codepen.io/kylokean/pen/XWXeWjL

<a href="#" class="change_img_wrap">
      <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
        <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
</a>

<a href="#" class="change_img_wrap">
  <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
    <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
</a>

<style>

.img-hover {
  display: none !important;
} 

.hideme {
  display: none !important;
}

.showme {
  display: block !important;
}

.change_img_wrap {
  display: inline-block;
} 

</style>

<script>

        jQuery(".change_img_wrap").hover(function() {
            jQuery(".img-regular").toggleClass("hideme");
        jQuery(".img-hover").toggleClass("showme");

        });

</script>
2 Answers
jQuery(".change_img_wrap").hover(function() {
  $(this).find(".img-regular").toggleClass("hideme");
  $(this).find(".img-hover").toggleClass("showme");
});

You need not specify the selector within the hover function. Instead handle it with this..

Here is a working snippet for your easy reference..

$(function(){
  $(".change_img_wrap").hover(function() {
    $(this).find('.img-regular').toggleClass('hideme');
    $(this).find('.img-hover').toggleClass('showme');
  });
});
.img-hover {
  display: none !important;
} 

.hideme {
  display: none !important;
}

.showme {
  display: block !important;
}

.change_img_wrap {
  display: inline-block;
} 
<html>

<head>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
   <a href="#" class="change_img_wrap">
      <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
      <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
   </a>

   <a href="#" class="change_img_wrap">
      <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
      <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
   </a>
</body>

</html>

Related