Collapse dropdown menu with JavaScript

0

I made the following code in JavaScript, so it would expand the dropdown, but now I do not know how I get it to pick up the menu, I wanted it when the "Focus" was not on the link, it collapsed (eg range of the menu):

$(document).ready(function() {
    $('li').click(function() {
        $('li.active').removeClass("active"); //aqui removemos a class do item anteriormente clicado para que possamos adicionar ao item clicado
        $(this).addClass("active"); //aqui adicionamos a class ao item clicado
    });
});

JSFiddle

    
asked by anonymous 25.09.2014 / 21:16

2 answers

2

In your code do so:

Pass the event in the click function of li and add the methods preventDefault and stopPropagation .

Example

Give the menu an absolute name:

<ul class="main-menu">

Specify best for who the click is:

$('.main-menu > li').click(function(event) {
    event.preventDefault();
    event.stopPropagation();
  

Note: The expression .main-menu > li means that the second element has to be   direct son of the first

And add the following event to html, body

$("html, body").click(function(event) {
    $('.main-menu > li.active').removeClass("active");
});

Now whenever the click is not on .main-menu > li or on your children, the active class will be removed from .main-menu > li elements.

Updated JSFiddle

Note: Do not set preventDefault or stopPropagation to the body event, otherwise it will cause default events such as buttons or links p>     

25.09.2014 / 21:26
1

I recommend that you use the mouseleave event to control this behavior, like this:

$(function() {
    $('li').on('click', function() {
        $(this).toggleClass("active");
    });

    $('li').on('mouseleave', function() {
        $(this).removeClass("active");
    });
});

Remembering that you need to leave the area of li .

JsFiddle

    
25.09.2014 / 21:38