Szekely Jonathan
Szekely Jonathan

Reputation: 137

Removing class from parent element

What I want to do is remove the open class from the dropdown div so the menu shows on hover and not on click, but I just can't get it removed. Maybe I don't understand how this works. All I know is that I managed to do it right until the mouseleave function. I'm using Bootstrap 3.

HTML

<div class="dropdown">
    <a data-toggle="dropdown" data-target="#" href="#" class="active"> Home <span class="main-text-color light">+</span> </a>
    <ul class="dropdown-menu" role="menu">
        <li>home shop</li>
        <li>home events</li>
        <li>home paralax</li>
        <li>home blog</li>
        <li>home portfolio</li>
        <li>home corporate : v1</li>
        <li>home corporate : v2</li>
        <li>home corporate : v3</li>
        <li>home corporate : v4</li>
        <li>home corporate : v5</li>
        <li>home corporate : v6</li>
        <li>create your own <i class="fa fa-play-circle-o"> </i> </li>
    </ul>
</div>

Javascript

$('.dropdown').hover(function () {
    $(this).addClass("open");
    $(this).children('.dropdown-menu').mouseleave(function () {
        $(this).parent().removeClass("open");
    });
});

Upvotes: 0

Views: 150

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Few observations

  • Since you have only one function callback for the hover call it will get executed on mouseenter and mouseleave event of the dropdown event
  • It will cause multiple mouseleave events being registered to the dropdown-menu element
  • Your code will not remove the open class if the user didn't enter the dropdown-menu element instead moved out of the dropdown without entering the dropdown-menu the dropdown will remain visible

I think this will do

$('.dropdown').hover(function () {
    $(this).addClass("open");
}, function () {
    $(this).removeClass("open");
});

Demo: Fiddle

Upvotes: 2

Related Questions