I want to have a very simple navigation menu. It has to be clickable. So when using this code
var isActive = true;
function toggleMenu(){
var content = $("#navContent");
isActive = !isActive; // toggle the current menu state
if(isActive) {
content.display = "block"; // show the items
} else {
content.display = "none"; // hide all items
content.position = "absolute";
content.zIndex = 1;
}
}
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="toggleMenu()">
<div id="navContainer">
<button id="navBtn" onclick="toggleMenu()">Menu</button>
<div id="navContent">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
</div>
</body>
and pressing on the menu button, I get into the toggleMenu() function but the items don't hide.
Can someone help me out?
$("#navContent")returns a jQuery object, but to directly access .style you would need the reference to a DOM element. But jQuery has methods to manipulate element styles, so there is not need to mix these two approaches in the first place. It has .show/.hide as well (although these are not the ideal way to do this either - you should rather just toggle a class, and leave formatting to your stylesheet.)toggle()for this and set the display to hidden in css to hide the menu upon page rendering but if you want to continue with the method you're using then you should be targeting thecssbefore trying to target and change acssproperty. Example:content.css("display", "block");