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.
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
Try .toggle()
$('.Menu').toggle(
function() {
//Do something
},
function() {
//Do Something Else
});
Also try #submenu{display:none;} instead of jQuery.
since CloseMenu class doesn't exist when you bind this event you need to do:
$(document).on('click', ".CloseMenu", function() {
$("#submenu").hide();
$(".CloseMenu").text("Menu");
$(".CloseMenu").removeClass( "CloseMenu" ).addClass( "Menu" );
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.