Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 977
It worked yesterday. Avatar asked Jun 18 '13 11:06

It worked yesterday.


2 Answers

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 !!

like image 109
adeneo Avatar answered Oct 24 '22 19:10

adeneo


This should solve your problem

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

div:hover {
    background-color: green;
}
like image 31
mohkhan Avatar answered Oct 24 '22 19:10

mohkhan