Fizzix
Fizzix

Reputation: 24365

How to detect if any elements currently have mouseenter active?

So basically, I have an un-ordered list with around 12 list items. I would like to apply a style to them when the mouse is over any of them, and a different style when the mouse is over none of them.

For example, the following is my current code that only has a style when li's are being hovered.

HTML:

<ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
    <li>List item 4</li>
    <li>List item 5</li>
    <li>List item 6</li>
</ul>

jQuery:

$('li').bind('mouseenter',function(){
    $(this).animate({'opacity': '1'},100,'easeOutBack');
});
$('li').bind('mouseleave',function(){
    $(this).animate({'opacity': '0.7'},600,'easeOutBack');
});

DEMO

I would like to style all the li to have opacity:1 when no li is being hovered over.

How can I achieve this?

Upvotes: 1

Views: 101

Answers (4)

Shomz
Shomz

Reputation: 37701

You can create a new class for the ul element that will cause all lis to be 100% opaque. Then, upon hovering a li, remove that class from the ul (its parent).

I'll give you a code if I sounded confusing.

Note that I've added a CSS transition, I suggest you do all of them using CSS (that way you won't have to deal with inline rules overriding all others).

$('li').bind('mouseenter',function(){
    $(this).animate({'opacity': '1'},100);
    $(this).parent().removeClass('full');
});
$('li').bind('mouseleave',function(){
    $(this).animate({'opacity': '0.7'},600, function(){
        $(this).css('opacity', '')
    });
    $(this).parent().addClass('full');
});

Here's what I had on my mind: http://jsfiddle.net/fqVT8/1/

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

You can do this with CSS only, if I understand correctly, you want to have all items at full opacity when none is hovered, and have full opacity on the one that's hovered and less opacity on the rest. Here's an example with just CSS:

li {
  opacity: 1;    
}

li:hover {
  opacity: 1 !important;
  transition: opacity .3s ease-in-out;
}

ul:hover li {
  opacity: .5;
  transition: opacity .3s ease-in-out;
}

Demo: http://jsfiddle.net/Sbgn8/2/

Upvotes: 4

Leo
Leo

Reputation: 14820

Can't you just change the selector inside the handler function? Changing this...

$(this).animate({'opacity': '1'},100,'easeOutBack');

to this....

$('li').animate({'opacity': '1'},100,'easeOutBack');

Upvotes: 0

juvian
juvian

Reputation: 16068

Is this what you want?

$('li').bind('mouseenter',function(){
     $(this).animate({'opacity': '1'},100,'easeOutBack');
});
$('li').bind('mouseleave',function(){
    $(this).animate({'opacity': '0.7'},600,'easeOutBack');
});
$("ul").bind('mouseenter',function(){
    $("li").animate({'opacity': '0.7'},200,'easeOutBack');
})
$("ul").bind('mouseleave',function(){
    $("li").animate({'opacity': '1'},200,'easeOutBack');
})

Upvotes: 1

Related Questions