1

I want when mouse goes on li jquery add a class to the element:

<ul class="menu">
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
</ul>

<script type="text/javascript">
var myMenu = $('.menu').children('li');

myMenu.on({
  mouseenter: function() { $( this ).addClass( "is_hovered" ); },
  mouseleave: function() { $( this ).removeClass( "is_hovered" ); }
});
</script>

But I want to remove class only if mouse goes on another li, if not keep class on element.

Is this possible?

0

2 Answers 2

5

Don't use the mouseleave handler in that case, on mouseenter remove the hovered class from other elements

var myMenu = $('.menu li');

myMenu.mouseenter(function () {
    myMenu.filter('.is_hovered').removeClass("is_hovered");
    $(this).addClass("is_hovered");
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

This will work, when you mouse over li it will add is_hovered to li and remove from other li.

$(".menu li").mouseover(function(){
    $(".menu li").removeClass("is_hovered");
    $(this).addClass("is_hovered");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.