Reputation: 93
All I want is that on item1
click to hide all items where id isn't item1
.
The html:
<span id="select1">item1</span>
<span id="2">item1</span>
<div style="clear:both"></div>
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item2">
<img src="http://www.lorempixel.com/100/100" id="item3">
<img src="http://www.lorempixel.com/100/100" id="item4">
<img src="http://www.lorempixel.com/100/100" id="item2">
This is the demo version: Demo
Upvotes: 1
Views: 91
Reputation: 666
Using same id for the different elements is not a good approach. Instead use it this way.
$('#select1').click(function(){
$(".item1").hide();
});
I have updated your fiddle and im attaching it along with the answer. Refer the fiddle:http://jsfiddle.net/eRg7h/2/
Upvotes: 0
Reputation: 74738
Having same ids for multiple element in a single page is validated as an invalid markup. As per standards ids should be unique per element, so you just can not do this.
To overcome this issue you can change your id
attribute to class
and you can try this code:
<span id="item1">item1</span> <!--do id like this-->
<span id="item2">item2</span> <!--do id like this-->
<div style="clear:both"></div>
<img src="http://www.lorempixel.com/100/100" class="item1"> <!--changed id to class-->
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">
$(function(){ // doc ready block starts
$('span[id^="item"]').on('click', function () {
var show = this.id; // "item1" if item1 clicked
$('img').hide(); // hide all img first
$('.' + show).show(); // show only click matched
});
});
Upvotes: 0
Reputation: 375
Your current code on there is simply missing the hash # before item1.hide()
$('#select1').click(function(){
$('#item1').hide();
});
Madhu above is correct though. Consider changing to classes instead of ids if you will have repeat elements.
Upvotes: 0
Reputation: 218
After changing to class like Madhu suggested, user proper class selector in jquery $(".item1").hide();
Upvotes: 0
Reputation: 7722
As Madhu says, it is not validable HTML, but if you want to continue with it: http://jsfiddle.net/5kJTU/
$('#select1').on('click',function(){
$('img').not("#item1").hide();
});
Upvotes: 1