Reputation: 1580
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?
Upvotes: 0
Views: 2033
Reputation:
Why not simplify it to:
$("#navBtn").click(function() {
$("#navContent").toggle();
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent {
display: none;
}
#navContent button {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="navContainer">
<button id="navBtn">Menu</button>
<div id="navContent">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
</div>
</body>
Upvotes: 0
Reputation: 722
It would be much easier to make a CSS class that hides the elements, which is then toggled by JS. This answer doesn't require jQuery
function toggleMenu(){
document.getElementById('navContent').classList.toggle("hidden")
}
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
}
.hidden {
display: none;
}
<div id="navContainer">
<button id="navBtn" onclick="toggleMenu()">Menu</button>
<div id="navContent" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
</div>
Upvotes: 0
Reputation: 337560
Your code is a rather odd mix of plain JS and jQuery. I'd suggest using one or the other. Here's a simple version of your code using jQuery:
$(function() {
$('#navBtn').click(function() {
$('#navContent').toggle();
});
});
#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>
<div id="navContainer">
<button id="navBtn">Menu</button>
<div id="navContent">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
</div>
Upvotes: 3