Jquery toggle display
I would like to create a list box and be able to toggle the display of children on click. Should be simple, but I can't seem to get it to work. Any thoughts?
<script>
$(document).ready(function(){
$("dt a").click(function(e){
$(e.target).children("dd").toggle();
});
});
</script>
<style>
dd{display:none;}
</style>
<pre>
<dl>
<dt><a href="/">jQuery</a></dt>
<dd>
<ul>
<li><a href="/src/">Download</a></li>
<li><a href="/docs/">Documentation</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
</dd>
<dt><a href="/discuss/">Community</a></dt>
<dd>
<ul>
<li><a href="/discuss/">Mailing List</a></li>
<li><a href="/tutorials/">Tutorials</a></li>
<li><a href="/demos/">Demos</a></li>
<li><a href="/plugins/">Plugins</a></li>
</ul>
</dd>
</dl>
</pre>
There are a couple of problems here.
-
$ ("dt a") - your selector is wrong because you don't have any "a" references. Should be $ ("dt")(I was basing this on the original malformated html - when I got this from the source it had no links) -
$ (e.target) .children ("dd") is incorrect because "dd" is a child of dt in your HTML.
Here's a working example:
$(document).ready(function() {
$("dt a").click(function(e) {
$(e.target).parent().next().toggle();
return false;
});
});
source to share
The other respondents are correct that your selector dd
is wrong. e.target
- this a
that has only text as its child, not the dd
one you are looking for. And as Mark pointed out (edit: before he deleted his answer) you want return false
from a click handler.
I like working with classes when doing this kind of thing, as it makes the code explicit and doesn't depend on the DOM structure.
Something like that:
<script>
$(document).ready(function(){
$("dt a").click(function(e){
// Toggle elements whose class is named by the anchor class
$('dd.'+this.className).toggle();
return false;
});
});
</script>
<style>
dd{display:none;}
</style>
<pre>
<dl>
<dt><a class='jQuery' href="/">jQuery</a></dt>
<dd class='jQuery'> <!-- Set the class name to the anchor class -->
<ul>
<li><a href="/src/">Download</a></li>
<li><a href="/docs/">Documentation</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
...
If you don't care about changing your structure, however, tanathos's solution will work just fine.
source to share