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()
<div id="clickables">
<div>CLICK 1</div>
<div>CLICK 2</div>
</div>
<div id="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
<div id="menu">
<div class="clickable">CLICK 1</div>
<div>text 1</div>
<div class="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();
});
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:
<div class="clickable" data-hidden="d1">CLICK 1</div>
<div id="d1" class="hidden">text 1</div>
<div class="clickable" data-hidden="d2">CLICK 2</div>
<div id="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.
Post a Comment for "Hide And Show Divs With Text"