Reputation: 1090
I have found a tutorial on some dropdown menu using jquery. It works fine but I want to adjust it just a little. Instead of hiding the menu using hovering, I want to have the same button that showed the menu, to hide it when it is being pressed again. So the same button has to both hide and show the dropdown menu. The script that im using:
$(document).ready(function () {
$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled - Adds empty span tag after ul.subnav
$("ul.topnav li span").click(function () { //When trigger is clicked...
//Following events are applied to the subnav itself (moving subnav up and down)
$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
$(this).parent().hover(function () {
}, function () {
$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
});
//Following events are applied to the trigger (Hover events for the trigger)
}).hover(function () {
$(this).addClass("subhover"); //On hover over, add class "subhover"
}, function () { //On Hover Out
$(this).removeClass("subhover"); //On hover out, remove class "subhover"
});
});
Upvotes: 1
Views: 1471
Reputation: 3639
Yes, toggleClass can be used. Or you can also define your own toggle function in javascript. you can toggle between the classes or do any other function you want to.
function tog(elemen){
if(elemen.className == "show") {
hide drpdwn
elemen.className="hide";
} else {
make dropdwn visible
elemen.className="show";
}
}
Upvotes: 1
Reputation: 7295
jQuery.toggle() function will do this work for you:
$("#button").on('click', function() {
$("#menu").toggle();
});
Upvotes: 1
Reputation: 16050
You can save yourself from adding a CSS rule by using jQuery's .toggle
method.
$('#yourMenu').toggle()
This will hide it if it's visible, and show it if it's hidden. You can add a number or 'fast', 'slow'
as a parameter to make it animate.
Upvotes: 1
Reputation: 1264
Use jQuery's .toggle()
http://api.jquery.com/toggle/
$("#yourbutton").click(function() {
$("#yourmenu").toggle();
});
Upvotes: 4