CLiown
CLiown

Reputation: 13853

jQuery - IF then Remove class on .hover

I have the following jQuery function:

$(function(){
            if ($(".menu li").hasClass("active")) {
                    $(".active").css("margin-top", "6px");
              }
        });

This is applied to a CSS/jQuery menu, which expands and contracts when each menu item is hovered over. The onClick event adds a margin-top of 6px to give the impressions of a button depress.

I'm then using PHP to detect which page the user is visiting to add an .active class to the relevant menu item.

The question, the .active class should remain in place until the user hovers over a different menu item. At which point the .active class should be removed from this element - As the .active class is reused on the .hover events.

Here is the basic HTML Markup:

<ul id="menu">
<li>
<div class="inner">
<div class="button"><img src="images/insightbutton.png" /></div>
<div class="description">&nbsp;</div>
</div>
</li>
<li>
<div class="inner">
<div class="button"><img src="images/insightbutton.png" /></div>
<div class="description">&nbsp;</div>
</div>
</li>
</ul>

How can I keep the .active class applied to the active menu item, but remove it when .inner is hovered over?

Upvotes: 1

Views: 2939

Answers (2)

Nick Craver
Nick Craver

Reputation: 630627

You could do this:

$(".menu li.active").addclass("onPage");
$(".menu li").hover(function() {
  $(".menu li.active").removeClass("active");
  $(this).addClass("active");
}, function() {
  $(this).removeClass("active");
  $(".menu li.onPage").addClass("active");
});

This code does the following:

  • Assigns a placeholder class to the original active (assigned by your PHP).
  • On hover, removes the active class from all <li> siblings and sets the hovered to one to active.
  • On leaving hover, it removes active from itself and selects the placeholder and restores active to the original (the page they're on).

Upvotes: 1

user229044
user229044

Reputation: 239551

You can simply select the div which has the active class, and remove the class:

$('div.inner').hover(function() {
    $('div.active').removeClass('active');
});

Upvotes: 0

Related Questions