Search code examples
jquerybuttonshow-hide

Switchout images with jquery


I have multiple images and for each image a button. Now I want to switch between the images on click of the corresponding button.

So when I click Button wiht value X all images hide except the image with the id X

<div class="variantImage" id="831">
  <img src="yy.jpg">
</div>
<div class="variantImage" id="1556">
  <img src="xx.jpg">
</div>

<button type="button" class="variantBtn" name="button" value="831">
  Format F4
</button>
<button type="button" class="variantBtn" name="button" value="1556">
  Format A1
</button>

This almost works:

$(".variantBtn").click(function(){
  var firedBtn = $(this).val();
  console.log(firedBtn)
  if(firedBtn){
    $("#" + firedBtn).css("display", "block");
  } else {
    $(".variantImage").not("#" + firedBtn).css("display", "hide");
      }
}).change();

On the first click the corresponding image shows up. but on the next click there is no more happening. I think Im close. But how do I hide every id excepte the corresponding one? https://codepen.io/Sepp/pen/wxgvmo


Solution

  • firedBtn will be always considered as true in your code you're just showing a new one not hiding other this should works as a solution :

    $(".variantBtn").click(function(){
       var firedBtn = $(this).val(); // console.log(firedBtn); //value of the btn
       $(".variantImage").hide(); //hide all image by class
       $("#" + firedBtn).show(); // show the image by id
    });