It worked yesterday.
It worked yesterday.

Reputation: 4617

Animating mouse leave with CSS and jQuery?

I am using CSS transitions to animate a background colour on mouse hover.

I have the following code:

div {
  width: 100px;
  height: 100px;
  background: red;
}

div:hover {
  background: green;
  transition: all 0.5s ease-in-out;
}
<div></div>

This code only animates the background colour on mouse on. It doesn't reanimate the mouse off. I have 2 questions:

  1. How do I animate the mouse off using CSS?

  2. How do I do this using jQuery only?

jsfiddle: http://jsfiddle.net/fz39N/

Upvotes: 14

Views: 35602

Answers (2)

adeneo
adeneo

Reputation: 318182

1) You change your css to

div {
    width: 100px;
    height: 100px;  
    background: red;
    transition: background 0.5s ease-in-out;
}

div:hover {
    background: green;

}

FIDDLE

setting the transition to the element, and not the pseudo class.


2)

With jQuery you'll either need two elements to cross fade, or a color animation plugin. jQuery UI has color animation built in, and then you can do :

$('div').on({
    mouseenter: function() {
        $(this).animate({backgroundColor: 'green'},1000)
    },
    mouseleave: function() {
        $(this).animate({backgroundColor: 'red'},1000)
    }
});

FIDDLE

If you're not already using jQuery UI for something else, I'd suggest using one of the much smaller plugins, like this one !!

Upvotes: 24

mohkhan
mohkhan

Reputation: 12305

This should solve your problem

div {
    width: 100px;
    height: 100px;  
    background-color: red;
    transition: background-color 0.5s;
}

div:hover {
    background-color: green;
}

Upvotes: 3

Related Questions