Reputation: 861
I have a JavaScript menu that I want to unfold/fold when I click on the #dropdown
button. First, it took three clicks for it to unfold and after those three clicks, it worked perfectly fine.
I edited my code, I have to click it three times again for it to work, but after that, each click makes the menu fold/unfold three times in a row.
buttonClickHandler
function buttonClickHandler(e) {
e.preventDefault();
$(document).ready(function(){
$('#main').hide();
$('a#dropdown-button').click(function(){
$('#main').toggle(function(){
$('#main').addClass('active').fadeIn();
}, function(){
$('#main').removeClass('active').fadeOut();
return false;
});
});
});
}
Init
function init(){
var button = document.getElementById('dropdown-button');
button.addEventListener("click", buttonClickHandler, false);
}
window.addEventListener("load", init, false);
HTML
<section id="nav-bar">
<figure>
<span class="helper"></span><img src="img/Logo.png" alt="Zien Woningmarketing"/>
</figure>
<a href="#" id="dropdown-button"><img src="img/Menu.png" alt="Menuknop: open het menu"/></a>
</section>
<nav id="main">
<ul id="firstLevel">
<li><a href="index.html">Home</a></li>
<li><a href="fotografie.html">Producten</a></li>
<li><a href="marketing.html">Woningmarketing</a></li>
<li><a href="over.html">Over Zien!</a></li>
<li><a href="werkwijze.html">Werkwijze</a></li>
</ul>
<ul>
<li class="login"><a href="#">Inloggen</a></li>
<li><a href="#">Registreren</a></li>
</ul>
</nav>
The thing is that this menu should easily drop down, thus showing its contents.
Upvotes: 0
Views: 1319
Reputation: 352
Hope this help : http://jsfiddle.net/x7xu4/2/
$(function(){
$("a#dropdown-button").on("click",function(event ){
$("#main").toggleClass('active').fadeToggle();
event.preventDefault();
});});
Since you are using jquery 2.1, instead of "click" use "on" for it saves a bit of memory, and I edited your code for a simpler solution.
Upvotes: 1
Reputation: 346
I make simpler your code
$(function(){
$('a#dropdown-button').click(function(){
if(!$('#main').hasClass('active')){
$('#main').addClass('active');
$('#main').show();
}else {
$('#main').removeClass('active');
$('#main').hide();
}
return false;
});
});
Here is jsFiddle sample
Upvotes: 0