David F. David F. - 1 month ago 7
HTML Question

jQuery menu not hiding on second click

I am trying to learn some jquery and I want to make a simple drop down that is hidden at the start but then appears when you click some text but then hides when you click it again. Here is the Code:

Basic HTML:

<h1 class="Menu">Menu</h1>

<div id="submenu">
<ul>
<a href="#"><li>Menu 1</li></a>
<a href="#"><li>Menu 2</li></a>
<a href="#"><li>Menu 3</li></a>
<a href="#"><li>Menu 4</li></a>
<a href="#"><li>Menu 5</li></a>
<a href="#"><li>Menu 6</li></a>
</ul>
<div>


The jQuery:

$(document).ready(function() {
$("#submenu").hide();
});

$(".Menu").click(function() {
$("#submenu").show("slow");
$(".Menu").text("Close Menu");
$(".Menu").removeClass( "Menu" ).addClass( "CloseMenu" );
});
$(".CloseMenu").click(function() {
$("#submenu").hide();
$(".CloseMenu").text("Menu");
$(".CloseMenu").removeClass( "CloseMenu" ).addClass( "Menu" );
});


Is it because the class wasn't registered into the DOM at page load so it doesn't know what it is looking for? Also here is the JS Fiddle I was doing it in.

Answer

Here, use this js code

$(document).ready(function() {
   $("#submenu").hide(); 
});

$("#mainmenu").click(function() {
    if($("#submenu").is(":hidden")){
        $("#submenu").show("slow");
        $(".Menu").text("Close Menu");
        $(".Menu").removeClass( "Menu" ).addClass( "CloseMenu" );
    }
    else{
        $("#submenu").hide();
        $(".CloseMenu").text("Menu");
        $(".CloseMenu").removeClass( "CloseMenu" ).addClass( "Menu" );
    }
});

Reason for not working is that you are changing the class at runtime. Use .click, only when you have static selectors. Like i used ID

Comments