Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to hide/show divs with JQuery

Tags:

html

jquery

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>
like image 975
Michael Tot Korsgaard Avatar asked Nov 03 '22 02:11

Michael Tot Korsgaard


2 Answers

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/

like image 161
dfsq Avatar answered Nov 09 '22 08:11

dfsq


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>
like image 38
Nick Andriopoulos Avatar answered Nov 09 '22 06:11

Nick Andriopoulos