I am trying to make a page with tag buttons that can show/hide elements according with their tag. This is my first version without loops:
https://jsfiddle.net/Pokipsy/uu7y3x2x/
$(document).ready(function(){
$(".showall").click(function(){
$(".item").show();
$(".filter").text("All elements")
});
$(".show.a").click(function(){
$(".item").hide();
$(".item.a").show();
$(".filter").text("Tag: a")
});
$(".show.b").click(function(){
$(".item").hide();
$(".item.b").show();
$(".filter").text("Tag: b")
});
$(".show.c").click(function(){
$(".item").hide();
$(".item.c").show();
$(".filter").text("Tag: c")
});
});
.clickable:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="clickable showall">all</li>
<li class="clickable show a">a</li>
<li class="clickable show b">b</li>
<li class="clickable show c">c</li>
</ul>
<h3 class="filter">
All elements
</h3>
<ul>
<li class="a item">first a</li>
<li class="b item">second b</li>
<li class="a b item">third a b</li>
<li class="c item ">fourth c</li>
<li class="c b item">fifth c b</li>
</ul>
It works but this strategy would produce a very long code if the tags are too many so I tried to use loops to make a shorter code that works with an array of tags:
https://jsfiddle.net/Pokipsy/f9uqetnn/1/
$(document).ready(function(){
$(".showall").click(function(){
$(".item").show();
$(".filter").text("All elements")
});
var tags = [".a",".b",".c"];
for(i = 0; i < 3; i++) {
x=tags[i];
$(".show".concat(x)).click(function(){
$(".item").hide();
$(".item".concat(x)).show();
$(".filter").text("Tag: ".concat(x))
});
}
});
.clickable:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="clickable showall">all</li>
<li class="clickable show a">a</li>
<li class="clickable show b">b</li>
<li class="clickable show c">c</li>
</ul>
<h3 class="filter">
All elements
</h3>
<ul>
<li class="a item">first a</li>
<li class="b item">second b</li>
<li class="a b item">third a b</li>
<li class="c item ">fourth c</li>
<li class="c b item">fifth c b</li>
</ul>
but it doesn't work: apparently it always recognise a click to the last element of the array even if I clicked the first. Is there a problem with jQuery that I am unable to see?