alibaba231654
alibaba231654

Reputation: 3

Remove Class From Element With Added Class

Trying to build a dropdown menu. The idea is to add class to parent and child on parent hover, and remove added class when mouse is out of both. This is html

<ul>
  <li class="menuitem"></li>
  <li class="menuitem">
    <ul></ul>
  </li>
  <li class="menuitem"></li>
</ul>

And this is jquery

$(".menuitem").each(function(){
  $(this).hover(function(){
    $(this).addClass("visible");
    $(this).find("ul").addClass("visible");
  });
});

$(".visible").each(function(){
  $(this).mouseout(function(){
    $(this).removeClass("visible");
  });
});

Upvotes: 0

Views: 45

Answers (2)

charlietfl
charlietfl

Reputation: 171700

hover() actually incorporates 2 events ... mouseenter and mouseleave. If you only provide one callback argument it gets used for both events.

If you provide 2 callbacks the first is for enter and the second is for leaving so you can do:

function enterEl(){
  $(this).addClass('visible').find('ul').addClass('visible');
}

function leaveEl(){
  $(this).removeClass('visible').find('ul').removeClass('visible')
}

$(".menuitem").hover(enterEl, leaveEl);

This is more verbose than using toggle methods but is to point out that you can do different things in the two event handlers.

This is also the same thing as doing

$(".menuitem") 
      .mouseenter(enterEl)
      .mouseleave(leaveEl);

Upvotes: 1

adeneo
adeneo

Reputation: 318342

The event handlers are bound to elements that match at the time of binding. Adding a class later doesn't make the event handler work for that class.

What you seem to be looking for, is just toggleClass

$(".menuitem").hover(function(){
    $(this).find('ul').addBack().toggleClass("visible");
});

FIDDLE

Upvotes: 2

Related Questions