Brum
Brum

Reputation: 691

Jquery add click event and remove it to others

How to automatically close a dropdown lists when the user click on another one? The purpose is no have only one dropdown list opened at time.

Jquery:

jQuery(".navbar-collapse .nav li").click(function(e) {

        if(jQuery(e.currentTarget).find("span").hasClass("clicked-li")) {
            jQuery(".navbar-collapse .nav li ul").removeClass("clicked");
            jQuery(".navbar-collapse .nav li span").removeClass("clicked-li");
        }

        if ((viewport().width <= 1200)) {
            if (!jQuery(e.currentTarget).find("ul").hasClass("clicked")) {
                jQuery(e.currentTarget).find("ul").addClass('clicked');
                jQuery(e.currentTarget).find("span").addClass('clicked-li');
            } else {
                jQuery(e.currentTarget).find("ul").removeClass('clicked');
                jQuery(e.currentTarget).find("span").removeClass('clicked-li');
            }
        }
    });

HTML:

<div class="navbar-collapse collapse in" aria-expanded="true" style="">
    <ul class="nav menu">
        <li class="item-101 default current active fa fa-chevron-down">
            <a href="/">Home</a><
        /li><li class="item-115 divider deeper parent fa fa-chevron-down">
        <span class="separator">XXX</span>
        <ul class="nav-child unstyled small">
            <li class="item-123 fa fa-chevron-down">
                <a href="XXX">XXX</a>
            </li>
            <li class="item-125 fa fa-chevron-down">
                <a href="XXX">XXX</a>
            </li><li class="item-126 fa fa-chevron-down">
                <a href="XXX">XXX</a>
            </li>
        </ul>
    </ul>
</div>

It seems to be pretty bugging out for me, does anyone know how to do this?

Upvotes: 0

Views: 89

Answers (1)

Xeff
Xeff

Reputation: 58

$('.clicked').removeClass('.clicked');

But make your code a snippet, that makes it easier to help you.

But anyways do it with CSS. Its much easier.

li {
  display: none;
}
a:focus li {
  display: block;
}
<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>

<body><ul>
<a href="#">HO

  <li>Hi</li>
  <li>Hi</li>
</a>
</ul><br>
<ul>
<a href="#">asdf
  <li>Hi</li>
  <li>Hi</li>
</a>
</ul>
</body>
</html>

Upvotes: 1

Related Questions