Search code examples
javascriptjqueryhtmlshow-hide

Hide/Show many elements on single click by jQuery


I've code few line of jQuery for Hide/Show many elements on single click and it's working. But problem is; i've many more image class items, so my script going to long, my question is how to simplify or make short my script, i mean any alternatives or any new idea? please suggest.

HTML:

<div id="choose-color">
<span>
 <i class="images-red" style="">Red Image</i>
  <i class="images-blue" style="display: none;">Blue Image</i>
   <i class="images-pink" style="display: none;">Pink Image</i>
 <!-- many many images -->
</span>

 <button class="red">Red</button>
  <button class="blue">Blue</button>
   <button class="pink">Pink</button>

</div>

JS: live demo >

$("button.red").click(function(){
    $(".images-red").show();
    $(".images-blue, .images-pink").hide();
});
$("button.blue").click(function(){
    $(".images-red, .images-pink").hide();
    $(".images-blue").show();
});
$("button.pink").click(function(){
    $(".images-red, .images-blue").hide();
    $(".images-pink").show();
});

Please suggest for short and simple code of my script. Thanks.


Solution

  • You can do it by adding just a common class to those buttons,

    var iTags = $("#choose-color span i");
    $("#choose-color button.button").click(function(){
        iTags.hide().eq($(this).index("button.button")).show();
    });
    

    The concept behind the code is to bind click event for the buttons by using the common class. Now inside the event handler, hide all the i elements which has been cached already and show the one which has the same index as clicked button.

    DEMO

    For more details : .eq() and .index(selector)

    And if your elements order are not same, both the i and button's. Then you can use the dataset feature of javascript to over come that issue.

    var iTags = $("#choose-color span i");
    $("#choose-color button.button").click(function(){
        iTags.hide().filter(".images-" + this.dataset.class).show()
    });
    

    For implementing this you have to add data attribute to your buttons like,

    <button data-class="red" class="button red">Red</button>
    

    DEMO