dmc dmc - 7 months ago 9
Javascript Question

Use more than one source to slide toggle an element

I've got a full screen slide down navigation menu with links which when clicked scroll to the relevant section . The menu is slide toggled by clicking on the #hamburger div . what i want is for the menu to slide out of view again when i click on a link but what happens is it slides up and then back down again

<div id="hamburger">
<nav id="navigation">
<ul>
<li><a></a></li>
<li><a></a></li>
<li><a></a></li>
</ul>
</nav>
</div>

<script>
$(document).ready(function(){
$("#hamburger , ul li a").click(function(){
$("#navigation").slideToggle("slow");
});
});
</script>

Answer

You have to stop the event-propagation,

$(document).ready(function(){
    $("#hamburger , ul li a").click(function(e){
        e.stopPropagation();
        $("#navigation").slideToggle("slow");
    });
});

When you are clicking over the anchor elements, the event will be propagated to the top until it reaches the document and during that time it crosses the #hamburger and it will also fire its click event. Hence the #navigation element is sliding up and down.

Comments