Liam Sorsby
Liam Sorsby

Reputation: 2972

Jquery on("click", function event

I currently have a very simple jquery function where if the menu is pushed then the menu is shown.

$(".menu").on("click", function( event ){
   $(".menulist").css("display","block");
   alert(event);
})

i would like to display none again if the menu button is clicked again or if they click off the menu.

i have tried the off function as follows but then realised it wouldn't work anyway:

$(".menu").off("click", function(){
   $(".menulist").css("display","none");     
})

any advise as to how to do this? if it helps this will be for a mobile website aswell

EDIT: the event is in the first function as i thought i might be able to use this event to tell if the item was already showing. either that or another though is would i be better on("click" function() to check if the css value of display for the .menu is equal to block or none and then alter the css from there? this would solve the click onto the menu button but not off the menu

Upvotes: 0

Views: 640

Answers (7)

Felipe Oriani
Felipe Oriani

Reputation: 38598

Try using the toggle method of jQuery:

$(".menu").on("click", function() {
    $(".menulist").toggle();
});

Upvotes: 1

kayen
kayen

Reputation: 4868

Use $(".menu").on("click", function(){ $('.menulist').toggle() }); to toggle the visibility of the menu list.

Update

To close the menu when you click off the menu element, just catch the click event on the body tag and close the menu if it is open:

The entire snippet would look something like this:

$('.menu').on('click', function(){ 
    $('.menulist').toggle();
});

$('body').on('click', function(e){
    if(!$(e.target).hasClass('.menu') && $('.menulist').is(':visible')) {
        $('.menulist').hide();
    }
});

Upvotes: 3

Somnath Kharat
Somnath Kharat

Reputation: 3600

As toggle() function is deprecated:

$(".menu").on("click", function( event ){
   if( $(".menulist").css("display")!="none")
    {
       $(".menulist").css("display","none");
    }
    else{
      $(".menulist").css("display","block");
   }
});

Upvotes: 0

Johan
Johan

Reputation: 35194

$(".menu").on("click", function(){
    var $menulist = $(".menulist");
    $menulist.toggle($menuList.is(":visible"));
}

Upvotes: 0

DrColossos
DrColossos

Reputation: 12988

$(".menu").on("click", function( event ){
   $(".menulist").toggle();
})

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

That is as Simply

$(".menu").on("click", function( event ){
   $(".menulist").toggle();
});

Upvotes: 0

Kevin Kulla
Kevin Kulla

Reputation: 460

$(".menu").on("click", function( event ){
   if($(".menulist:visible"))
   {
     $(".menulist").css("display","none");
    }else{
     $(".menulist").css("display","block");
   }
});

Upvotes: 0

Related Questions