Easier way to hide / show divs using jQuery

I want to hide all of them with a class .Hide, and then show a specific div according to the link I clicked on. I got it so far, but is there an 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>
+5
source share
5 answers

Data attributes can be options:

$(".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-somethingto refer to the corresponding element.

http://jsfiddle.net/dfsq/u8CAD/

+3
source

As of now, I think it’s as good as you can do it (you can put the hidden code in the function and link from all, but it’s about the same).

HTML rel, , ( .click(), jQuery .on()):

$('.btn').click(function() {
  $('.Hide').hide("fast");
  $('#'+$(this).attr('rel')).show("fast");
}

HTML

<a href="#" id="btn_one" class="btn" rel="one">one</a>
<div id="one" class="Hide">1</div>
+2

$("a.btn[id^=btn]").click(function() {
    $(".Hide").hide("fast");
    var id = $(this).attr('id').substring(4);
    $("#" + id).show("fast");
});

: Fiddle

+1

, div , :

<nav>
    <a href="#" class="btn">one</a>
    <a href="#" class="btn">two</a>
    <a href="#" class="btn">three</a>
</nav>

<div>
    <div class="Hide">1</div>
    <div class="Hide">2</div>
    <div class="Hide">3</div>
</div>

JavaScript

$('.btn').click(function() {
     $(".Hide").hide("fast").eq( $(this).index() ).show("fast");
});

Demo

http://jsfiddle.net/TUrgG/

data-* -.

0

-, :

$(".Hide").hide();

, DIV, . :

var id = $(this).attr("id").replace("btn_", "");

HTML .


However, I would recommend using the attribute data-*to store the identifier. A complete solution would look like this:

<a href="#" id="btn_one" data-showid="one" class="btn">one</a>
<a href="#" id="btn_two" data-showid="two" class="btn">two</a>
<a href="#" id="btn_three" data-showid="three" class="btn">three</a>

<div id="one" class="Hide">1</div>
<div id="two" class="Hide">2</div>
<div id="three" class="Hide">3</div>

with the following javascript / jQuery:

$(".btn").click(function(e){
   e.preventDefault();
   $(".Hide").hide();
   var id = $(this).data("showid");
   $("#" + id).show();
});

Here is a working example

-4
source

All Articles