Home > OS >  Change image on active parent div
Change image on active parent div

Time:09-02

I have this code in which the image changes when a parent div is in an active state but it how to undo it when I click it again? How to bring back the original image? I tried putting return false at the end but it didn't work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png">
 <div >
  <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3"/>
 </div>
</div>
$('.egg').click(function(){
  $(this).toggleClass("active");
  var new_src = $(this).attr('data-img');
  $(".card-image img").attr("src",new_src);
});

CodePudding user response:

You can keep track of the current img src before toggling its state, overwriting the same data attribute you use to store the alternative image.

In this demo I also better dealt with the selector you used to fetch the img element, restricting its action only to the img child embedded in the clicked .egg div:

$('.egg').click(function() {  
  const new_src = $(this).attr('data-img');  
  const curr_src = $(this).find('.card-image img').attr('src');
  $(this).attr('data-img', curr_src);
  
  $(this).toggleClass("active");  
  $(this).find('.card-image img').attr("src", new_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div  data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png">
  <div >
    <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3" />
  </div>
</div>

  • Related