Andy Mac Andy Mac - 2 months ago 10
Javascript Question

Image swap on image click with javascript if else

I am trying to swap an image on a click with javascript if else method. The first image swap works(if), but the other 2 dont(else if). Here is my JS/JQuery:

$("#right").on("click" ,

function() {

var pic = $("#selection img").attr("id");

if (pic == "instagram") {
$("#instagram").removeClass("show").addClass("hide");
$("#snapchat").removeClass("hide").addClass("show");
$("span").text("Snapchat");

}

else if (pic == "snapchat") {
$("#snapchat").removeClass("show").addClass("hide");
$("#twitter").removeClass("hide").addClass("show");
$("span").text("Twitter");
}

else if (pic == "twitter") {
$("#twitter").removeClass("show").addClass("hide");
$("#facebook").removeClass("hide").addClass("show");
$("span").text("Facebook");
}

});


Here is my CSS:

.hide {
display: none;
}

.show {
display: inline;
}


And here is my HTML:

<div id="selection">
<img id="instagram" class="show" src="img/instagram.png">
<img id="snapchat" src="img/snapchat.png">
<img id="twitter" src="img/twitter.png">
<img id="facebook" src="img/facebook.png">
</div>


Thank you for your answers !

Answer

You need to swap the classes between the indexes of the image.

This is considered as cycle, if your on the last index then it should start with first then.

Check the working snippet.

//Apply the hide to all the images except first one
$('#selection img').not(":eq(0)").addClass("hide");
var currentIndex=0;
var newIndex=0;
$("#right").on("click" , function() {
  //Check is it a last index
  var isLast = $('#selection img').last().hasClass('show');
  currentIndex = $('#selection img.show').index();
  //If it is last index then hide the same and show the first image
  if(isLast)
  {
          $('#selection  img:eq('+currentIndex+')')
              .removeClass('show')
              .addClass('hide');

          $('#selection  img:eq(0)')
              .removeClass('hide')
              .addClass('show');
  }
  else
  {
          $('#selection  img:eq('+currentIndex+')')
               .removeClass('show')
               .addClass('hide');

          $('#selection img:eq('+(currentIndex+1)+')')
              .removeClass('hide')
              .addClass('show');  
  }
  $('#output').html($('#selection img.show').attr('id'));
});
.hide {
display: none;
}

.show {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selection">
    <img id="instagram" class="show" src="img/instagram.png">
    <img id="snapchat" src="img/snapchat.png">
    <img id="twitter" src="img/twitter.png">
    <img id="facebook" src="img/facebook.png">
</div>
<span id="output"></span>
<a href="#" id="right">Right</a>