I want to hide all the ones with the class .Hide
and then show a specific div according to which link I clicked.
I got this so far, but is there a easier way?
My code so far: (using JQuery)
$(".btn").click(function (){
$(".Hide").hide("fast");
});
$("#btn_one").click(function () {
$("#one").show("fast");
});
$("#btn_two").click(function () {
$("#two").show("fast");
});
$("#btn_three").click(function () {
$("#three").show("fast");
});
HTML:
<a href="#" id="btn_one" class="btn">one</a>
<a href="#" id="btn_two" class="btn">one</a>
<a href="#" id="btn_three" class="btn">one</a>
<div id="one" class="Hide">1</div>
<div id="two" class="Hide">2</div>
<div id="three" class="Hide">3</div>
Data attributes could be an option:
$(".btn").click(function () {
$(".Hide").hide("fast");
$("#" + $(this).data('type')).show("fast");
});
HTML:
<a href="#" id="btn_one" data-type="one" class="btn">one</a>
<a href="#" id="btn_two" data-type="two" class="btn">one</a>
<a href="#" id="btn_three" data-type="three" class="btn">one</a>
You can use data-something
to refer corresponding element.
http://jsfiddle.net/dfsq/u8CAD/
As it is right now, I think that's about as good as you can make it (you could place the hiding code in a function and reference from all, but it's about the same).
If you can change the HTML code a bit, and add a rel
attribute to the buttons, containing the id of the related element, then you can really make the code better (I'm using .click()
but if your jQuery version allows you should change to .on()
):
$('.btn').click(function() {
$('.Hide').hide("fast");
$('#'+$(this).attr('rel')).show("fast");
}
And the relevant HTML
<a href="#" id="btn_one" class="btn" rel="one">one</a>
<div id="one" class="Hide">1</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With