dancemc15
dancemc15

Reputation: 628

How do I fade out multiple images using jquery?

I would like to fade out these 3 images on click with a 3 sec delay after clicking on the image. The code I've written currently does not work. Can someone explain why? Thank you! I thought 'this' would refer to the 3 id tags.

Also, if there is a simpler way, please share.

<script>

$(function(){
  ('#img1, #img2, #img3').click(function() {
    $(this).fadeOut(3000);
  });
});
</script>


<div class="flex-container">
 <img id="img1" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
 <img id="img2" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
 <img id="img3" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
</div>

</body>
</html>

Upvotes: 1

Views: 262

Answers (3)

Arun Sharma
Arun Sharma

Reputation: 1331

Follow this snippet.This is the simplest way to fade image with a delay. It fades images 3 seconds after the click event as required by you.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="flex-container">
 <img id="img1" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
 <img id="img2" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
 <img id="img3" src="http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2015/09/google_logo.jpg">
</div>

<script>
$(document).ready(function(){
var selector = '#img1,#img2,#img3';
    $(selector).click(function(){
      
        $(selector).delay(3000).fadeOut(1000);

    });
  
});
  

</script>

Upvotes: 1

Atula
Atula

Reputation: 2173

try this https://jsfiddle.net/pvfbsq3q/2/

$(document).ready(function() {  
   $(function(){
  $('#img1,#img2,#img3').click(function() {
    $('#img1,#img2,#img3').fadeOut(3000);
  });
});});

Upvotes: 1

Naveen Setty
Naveen Setty

Reputation: 625

fadeOut will fade images in 3 seconds, not after 3 seconds, use

$('.image').click(function() {
    setTimeout(function(){ 
        $(this).fadeOut(3000);
    }, 3000);
});

use common class for images, so that it can be extendable in near future. in call back fade images.

Upvotes: 2

Related Questions