-1

I'm trying to get my div element to change pictures. The problem I'm having is that all the div that I've selected are changing. I've tried the .each() function but I haven't been able to get it to work.

$('.product_category_item div').hover(function() {
  $('.main_image').each(function() {
    $(this).css("display", "none");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "block");
  });
}, function() {
  $('.main_image').each(function() {
    $(this).css("display", "block");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "none");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 product_category_item">
  <a href="taps.html">
    <div>
      <img class="main_image" src="img/water-faucet1.jpg">
      <img class="hover_image" src="img/gold-faucet1.jpg">
      <p>
        taps
      </p>
    </div>
  </a>
</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/block_seal.jpg">
    <img class="hover_image" src="img/round_seal.jpg">

    <p>
      seals
    </p>
  </div>
</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/hinge1.jpg">
    <img class="hover_image" src="img/hinge2.jpg">

    <p>
      hinges
    </p>
  </div>
</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/handle1.jpg">
    <img class="hover_image" src="img/handle2.jpg">

    <p>
      handles
    </p>
  </div>
</div>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
Isis
  • 189
  • 4
  • 16

1 Answers1

1

Try changing your code to below.

$('.product_category_item div').hover(function(){
   $(this).find('.main_image').hide(); 
   $(this).find('.hover_image').show();
}, function(){
   $(this).find('.main_image').show(); 
   $(this).find('.hover_image').hide();
});
Prashant Shirke
  • 1,423
  • 1
  • 8
  • 10
  • Thank you so much. That was it. I hadn't thought of using `find()` function – Isis Jun 08 '17 at 09:59
  • Welcome. Yeah, without `this` it gets all elements matching the selector throughout the DOM. Also you can keep hover images hidden bydefault `.hover_image {display:none}` – Prashant Shirke Jun 08 '17 at 10:00