Reputation: 28783
I have the following code: http://jsfiddle.net/YfzbZ/
HTML
<dl class="dropdown right">
<dt><a>Options</a></dt>
<dd>
<ul style="display:none;">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 1</a></li>
</ul>
</dd>
</dl>
JQUERY
$('dl.dropdown dt a').live('click', function () {
var clicked = $(this);
var toggleMenu = $(clicked).parents('dl').find('dd > ul');
// Remove selcted class from all menus
$('dl.dropdown dt a').removeClass('selected');
// Hide all Uls
$('dl.dropdown dd ul').hide();
// and remove selected class for inner Lis
$('dl.dropdown dd ul li').removeClass('selected');
// Toggle the menu on each click
$(toggleMenu).toggle();
// Toggle the class on the button
$(clicked).toggleClass('selected');
});
The idea is that a user clicks the options and it shows the UL. This is fine but on the second click it does not hide the menu again... Any ideas why? It is definitely toggling the correct menu but it's just not hiding it on the second click :/
Thanks
Upvotes: 0
Views: 247
Reputation: 5954
try this it works perfect
$('dl.dropdown dt a').live('click', function () {
var clicked = $(this);
var toggleMenu = $(clicked).parents('dl').find('dd > ul');
// Remove selcted class from all menus
$('dl.dropdown dt a').toggleClass('selected');
// Hide all Uls
$('dl.dropdown dd ul').slideToggle();
// and remove selected class for inner Lis
$('dl.dropdown dd ul li').toggleClass('selected');
// Toggle the menu on each click
$(toggleMenu).toggle();
// Toggle the class on the button
$(clicked).toggleClass('selected');
});
try this on JS Fiddle
Upvotes: 1
Reputation: 696
You should give slideToggle a chance.
I usualy use it for this purpose.
$('#book').slideToggle('slow', function() {
// Animation complete.
});
http://api.jquery.com/slideToggle/
Upvotes: 1
Reputation: 18776
comment out the line:
$('dl.dropdown dd ul').hide();
.toggle() will turn your menus on and off for you so because you have always 'hidden' your UL's .toggle() will always turn them back on.
Upvotes: 1
Reputation: 1677
I apologise but I cannot explain why it's not working exactly... What I can do to help though, is re-write your code in simply 3 line of javascript:
$('dl.dropdown dt a').live('click', function () {
$(this).closest('.dropdown').toggleClass('selected');
});
Example: http://jsfiddle.net/peduarte/YfzbZ/1/
Upvotes: 1