Jquery Toggle Dynamically
I want to toggle divs dynamically. Here is what I found so far... $('.toggle').click(function() { $(this).next('.container').toggle('fast'); }); What I have is this (HTML): <
Solution 1:
If you need/want to keep this DOM structure, you should use the index
.
$('.toggle').click(function() {
$('.container').eq($(this).index()).toggle('fast');
});
Example: http://www.jsfiddle.net/4yUqL/36/
Solution 2:
I think what you are looking for is
$(".toggle").click(function() {
$($('.container')[$(this).index(".toggle")]).toggle('fast');
});
Working fiddle
Solution 3:
You may try out the toggle feature of JQuery. And I will rather have some other dependency between the headers and the content divs, rather than trusting the order of their occurrence.
Solution 4:
if you change the order of your html:
<h4class="toggle">1</h4><divclass="container">Content1</div><h4class="toggle">2</h4><divclass="container">Content2</div><h4class="toggle">3</h4><divclass="container">Content3</div>
your code works, because it's just getting the next DOM element and toggling it if it matches the class. However it's pretty shaky and other people's examples that tell js more specifically what to do would be better.
Post a Comment for "Jquery Toggle Dynamically"