Collect dropdown menu with Javascript

Asked

Viewed 1,023 times

0

I made the following code in Javascript, for him to expand the dropdown, but now I do not know how to collect the menu, I wanted that when the "Focus" was not in the link, it collected (ex: clicking out of the reach 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

2 answers

2


In your code do like this:

Passes as parameter the Event in the click function of li and adds the methods preventDefault and stopPropagation.

Example

Give an absolute name to the menu:

<ul class="main-menu">

Better specify who the click is for:

$('.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 on html, body

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

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


Updated Jsfiddle

Note: do not put preventDefault nor stopPropagation in the event of body, otherwise it will give problem in the default events, for example buttons or links

  • Thanks for the help buddy, but so when I click on the sub-menu it closes too, have to keep it open?

  • Yes, just remove or comment on the line $('li.active').removeClass("active"); in the click event.

  • 1

    I updated Jsfiddle there, take a look. ;)

1

I recommend you use the event mouseleave to control such behaviour:

$(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

  • I liked your code, but as I will use it to touch too, I need something that has to do with clicking, can be clicking again on the link.

  • I edited my answer to have the click show/hide. I just replaced the addClass of Event delegate click for toggleClass, which checks whether the class is present and removes it, and vice/versa.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.