How to show CSS transitions only on hover?

I added a transition to the div, so when it freezes, the color changes, as in the example below: http://jsfiddle.net/78LWT/

Here is the HTML code:

<div id="transition"></div> 

Here is the CSS code:

 #transition { background-color: #DA1E1E; width: 100px; height: 100px; transition: .5s background-color; -webkit-transition: .5s background-color; -moz-transition: .5s background-color; } #transition:hover { background-color: #ADE1E1; } 

But here is the problem: http://jsfiddle.net/E295T/ (same CSS code as before), with this HTML code:

 <div id="transition"></div><br /> <button onclick="recolortransitiondiv();">Recolor that div!</button> 

And this JavaScript / jQuery code:

 function recolortransitiondiv() { $("#transition").css("background-color", "#1EDA1E"); } 

And where my problem arises. When the color should be changed in any way, except hovering over it (for example, when the div is active or, possibly, when the div properties are changed using JavaScript / jQuery) I do not want the transition to be displayed, but I want the transition to be displayed when I hover over a div.

Is there any way to solve this problem? I am ready to use jQuery, simple JavaScript, CSS and HTML.

+6
source share
1 answer

As you commented, if you want to prevent transition while background-color changed using button , the way to do this is to use transition in a block :hover

 #transition:hover { background-color: #ADE1E1; transition: .5s background-color; -webkit-transition: .5s background-color; -moz-transition: .5s background-color; } 

Demo 2 ( background-color will not change, read on)

Note. In any case, you will also need the solution below, otherwise the background-color will not be changed

Demo 3 (If you want :hover even after changing background-color using jQuery)


This is because jQuery adds inline CSS, which has the most preference / most specific and therefore :hover background-color will not be respected, you will have to use !important in this case

Demo

 #transition:hover { background-color: #ADE1E1 !important; } 

Or it would be better if you prefer to add and remove a class using jQuery instead of using the .css() method, which you won't need !important .

+8
source

All Articles