Hide / Show multiple items with one 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.


<div id="choose-color">
 <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 -->

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


JS: live demo >

    $(".images-blue, .images-pink").hide();
    $(".images-red, .images-pink").hide();
    $(".images-red, .images-blue").hide();

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

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(){

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.


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>