Search code examples
jqueryonclickbuttonclick

Change to the next image when clickon button using jquery


**I want to change to the next image when clicking on button using jquery, displaying one image at a time, should I use hide/show, display: none or .remove/.append? **

$("#next").toggle(function(){
  function(){
    $('#planet1').remove();
    $('#planet2').append();
  });
  function(){
    $(this).remove('#planet2').append('#planet3');
  });
  function(){
    $(this).removeClass('planet3').addClass('planet4');
  });
  function(){
    $(this).removeClass('planet4').addClass('planet5');
  });
});
          <div class="planets">
              <img id="planet1" src="img\planets\planet1.png" />
              <img id="planet2" src="img\planets\planet2.png" />
              <img id="planet3" src="img\planets\planet3.png" />
              <img id="planet4" src="img\planets\planet4.png" />
              <img id="planet5" src="img\planets\planet5.png" />
          </div>
              <button id="next"> Make a greener planet</button>


Solution

  • Here is a way to accomplish what you are looking for with some basic jQuery and CSS. First, you will set all images to be hidden by default, with only the first shown.

    img:first-of-type {
      display: inherit;
    }
    
    img {
      display: none;
    }
    

    Then you can have a function that rotates through.

    $('#next').click(function() {
      currentPicture++;
      if (currentPicture > $('img').length) {
        currentPicture = 1;
      }
      $('img').css('display', 'none');
      $(`#planet${currentPicture}`).css('display', 'inherit');
    });
    

    https://jsfiddle.net/hmnhdknL/1/