santa
santa

Reputation: 12512

Fade in/out label on hover

I have couple areas with labels. When I hover an area I would like to change the color of the label in that area to be more prominent and fade out the other labels in the areas that I am not hovering over.

How do I do that swap?

$("li").hover(function(){
    $(this).find(".label").fadeOut(100);
});

Upvotes: 1

Views: 2674

Answers (4)

Andreyco
Andreyco

Reputation: 22872

I created this example for you. It uses unordered list, with <span> tags inside, which are faded in/out.

<ul>
    <li><span>1st.</span> list item</li>
    <li><span>2nd.</span> list item</li>
    <li><span>3dr.</span> list item</li>
    <li><span>4th.</span> list item</li>
    <li><span>5th.</span> list item</li>
    <li><span>6th.</span> list item</li>
    <li><span>7th.</span> list item</li>
</ul>​

 

$('li').mouseenter(function(){
    $('span', this).stop().animate({opacity:1}, 150)
    $('span', $(this).siblings('li')).stop().animate({opacity:0.3}, 150)
})

When you hover the LI element, child span is faded to 100% and child spans of sibling LIs are faded to 50%;

$('ul').mouseleave(function(){
    $('span', this).animate({opacity: 1}, 150);
})​

When you leave parent UL element, all span elements are reverted back, animated to 100%;

Here is working example of this... http://jsfiddle.net/HBj4F/

Upvotes: 0

Jasper
Jasper

Reputation: 76003

Generally you pass two functions into .hover(). The first is the mouseover function and the second is the mouseout function.

JS --

$("li").hover(
    function () {
        $(this).find("label").stop().fadeTo(100, 1);
    },
    function () {
        $(this).find("label").stop().fadeTo(100, 0);
    }
);

CSS --

label {
    opacity : 0;
    filter  : alpha(opacity=0);
}​

The .stop() will allow the user to quickly mouse-over then out and the animation will not run all the way though, which creates a queue of animations if the user mouse overs and out a bunch fast. I used .fadeTo() with the .stop() because if you use .fadeOut()/.fadeIn() the animation can break when the user mouse overs and out quickly.

Another advantage to .fadeTo() is that we are only animating the opacity of the element, so the element still retains its position on the screen (i.e. elements don't jump around).

Here is a demo: http://jsfiddle.net/jasper/ExWQp/

Docs for .hover(): http://api.jquery.com/hover

Upvotes: 1

burak altundal
burak altundal

Reputation: 712

$("li").hover(
  function () {
    // hover active
  }, 
  function () {
    // hover deactive
  }
);

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71918

You should pass two functions to .hover. The first one will be used as a callback to mouseover, the second one to mouseout:

$("li").hover(
    function(){
        $(this).find(".label").fadeOut(100);
    },
    function(){
        $(this).find(".label").fadeIn(100);
    }
);

Upvotes: 2

Related Questions