Reputation: 1918
I'm having an issue writing this jQuery code.
What I want is to be able to click the option-menu
anchor tag and show the div
with the class name of the same id
so when I click option1
I'll be able to see all the divs that have the class of option1
Menu
<ul class="inline option-menu">
<li><a href="#" id="option1">option1</a></li>
<li><a href="#" id="option2">option2</a></li>
<li><a href="#" id="option3">option3</a></li>
</ul>
<div class="cover option1">
<p>test 1</p>
</div>
<div class="cover option3">
<p>test 2</p>
</div>
<div class="cover option2">
<p>test 3</p>
</div>
<div class="cover option1">
<p>Tester 4</p>
</div>
<div class="cover option2">
<p>test 5</p>
</div>
<div class="cover option1">
<p>test 6</p>
</div>
<div class="cover option3">
<p>test 7</p>
Upvotes: 1
Views: 851
Reputation: 1074495
You can get all of the elements whose id
s start with option
by using an attribute-starts-with selector:
$("[id^=option]")
You can handle clicks on them using .on("click", ...
or just .click(...
Within that handler, this
will be the DOM element that was clicked, so you can use this.id
to get its id
.
You can find elements with the relevant class using .
followed by the id
.
Since all of the options you want to hide have the class cover
, that makes it easy to hide them and then show (or filter out) the ones you want to show.
So:
$("[id^=option]").on("click", function() {
// Hide all
$(".cover").hide();
// Then show the ones that match this `id`
$("." + this.id).show();
});
Or if you're adding and removing options often, probably better to use a delegated version:
$(document).on("click", "[id^=option]", function() {
// Hide all
$(".cover").hide();
// Then show the ones that match this `id`
$("." + this.id).show();
});
If you want, you can get a bit fancier using .not
to avoid hiding elements inappropriately:
$(document).on("click", "[id^=option]", function() {
var selectorToShow = "." + this.id;
$(".cover").not(selectorToShow).hide();
// Then show the ones that match this `id`
$(selectorToShow).show();
});
Normally that doesn't matter much, but if you have CSS transitions on them or something...
Upvotes: 3