Skip to content Skip to sidebar Skip to footer

Hide And Show Divs With Text

I know there are a lot of these threads but none seem to really fit me. I have 5 dives with text like 'this is div1, to div5'. These are always gonna be shown. And i have 5 hidden

Solution 1:

This are the most used techniques:

target element using .index() and .eq()

<divid="clickables"><div>CLICK 1</div><div>CLICK 2</div></div><divid="togglables"><div>text 1</div><div>text 2</div></div>

$(function(){

    $("#clickables div").click(function(){
         var idx = $(this).index();
         $('#togglables div').eq( idx ).slideToggle();
    });

});

Pros: you can keep a really clean HTML markup, no need to assign additional classes or ID Cons: don't put other elements inside the parents otherwise you might mess the index count


target element using .next()or other jQuery traversal methods

<divid="menu"><divclass="clickable">CLICK 1</div><div>text 1</div><divclass="clickable">CLICK 2</div><div>text 2</div></div>

$(function(){

    $("#menu .clickable").click(function(){
         $(this).next('div').slideToggle();
    });

});

target specific element using ID

    <div class="clickable"id="_1" > CLICK 1 </div>
    <div class="clickable"id="_2" > CLICK 2 </div>

    <div id="togglable_1"> text 1 </div>
    <div id="togglable_2"> text 2 </div>

$(function(){

    $(".clickable").click(function(){
         $("#togglable"+ this.id).slideToggle();
    });

});

Pros: You can target elements unlogically positioned in the DOM Cons: Verbose HTML; Unflexible and hardly maintainable code.

Solution 2:

$('div').click(function() {
    var text = $(this).text();
    $('#'+text).show();
});

FIDDLE DEMO

Solution 3:

As @Roko C. Buljan nicely showed there are many ways of doing it.

This is how I usually do using .data() jQuery function:

<divclass="clickable"data-hidden="d1">CLICK 1</div><divid="d1"class="hidden">text 1</div><divclass="clickable"data-hidden="d2">CLICK 2</div><divid="d2"class="hidden">text 2</div>

$(".clickable").click(function() {
    $("#" + $(this).data("hidden")).toggle();  
});

This way it does not matter how I organize my DOM elements. I only need to care to identify the right id in every data-hidden attribute.

Working demo

Post a Comment for "Hide And Show Divs With Text"