Furious Furious - 3 months ago 12
CSS Question

How to change images with just one button with jq

I am newbie to programming, but still learning...

My problem is: I want to change images, three of them, with one button and with some

fadeIn
and
fadeOut
animation. So, first all of them (images) are hidden,then with a single click first picture appear with fadeIn effect, then with next single click first picture disappear and second picture appear and so on...

This is my html..

<button id="animeButton">Animate</button> <br>
<img id="firstPic" class="images" src="http://paladone.com/
image/cache/data/Pacman/PP2723PM_pac_man_ghost_pixel_bricks-800x800.jpg">
<img id="secondPic" class="images" src="http://i2.wp.com/loyalkng.com/wp-
content/uploads/2009/05/furious-george.jpg?w=557">
<img id="thirdPic" class="images" src="http://www.wallpaperist.com/
wallpapers/Cartoons/Donald-duck-furious-800-600.jpg">


This is my jq...

$(document).ready(function() {
$(".images").hide();
});

$(document).ready(function(){
$("#animeButton").click(function(){
$("#firstPic").fadeIn(2000);
//dunno what to write next....
});
});

Answer

This will work, check it out:

$(document).ready(function() {
  $('.images').hide();

  var counter = 0;
  var picArray = [];

  $("div").find("img").each(function(index, value) {
    picArray[index] = $(this);
  })

  $('#animeButton').click(function() {
    if (counter == 0) {
      picArray[picArray.length - 1].fadeOut(2000, function() {
        picArray[counter].fadeIn(2000);
        counter++;
      })

    } else {
      picArray[counter - 1].fadeOut(2000, function() {
        picArray[counter].fadeIn(2000);
        counter++;
        if (counter > picArray.length - 1) {
          counter = 0;
        }
      })
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="animeButton">
  Animate
</button>
<br/>

<div>
  <img id="firstPic" class="images" src="http://paladone.com/image/cache/data/Pacman/PP2723PM_pac_man_ghost_pixel_bricks-800x800.jpg">

  <img id="secondPic" class="images" src="http://i2.wp.com/loyalkng.com/wp-content/uploads/2009/05/furious-george.jpg?w=557">

  <img id="thirdPic" class="images" src="http://www.wallpaperist.com/ 
wallpapers/Cartoons/Donald-duck-furious-800-600.jpg">
</div>

Comments