2

I have a button with hover effect on it (color changes).

button {
    width: 180px;
    height: 80px;
    background-color: #A0522D;  
}

button:hover {
    background-color: #CD853F;
}

Then, from js I want to change background-color, for example when the button chosen is correct one. That is what I came up with:

buttons[i].style.backgroundColor = "#A0522D";

I also have transition property for animation:

button {
    transition: background 0.5s ease, color 0.2s ease;
}

It appears that whenever I change background-color for the first time, it completely removes hover animation. That is not the case when I change font color, not background color, though.

Do you have any idea how to have both hover animation and js animation changing bgcolor working at the same time? Or could it be that my approach to animate buttons is not right?

OnaBai
  • 40,767
  • 6
  • 96
  • 125
msgmaxim
  • 788
  • 2
  • 8
  • 15

3 Answers3

3

This has to do with the specificity of your CSS rules. Rules set on the element (by setting the style property, for instance) will have higher specificity than those you declare in a CSS file/style block (unless you use !important).

The better approach would be to use classes to set the background property and to change those on the element instead of setting the style directly:

buttons[i].className = "myClass";

This StackOverflow answer has a great description of how to set CSS classes in javascript. You can read more details about CSS specificity in this article.

Community
  • 1
  • 1
cfs
  • 10,610
  • 3
  • 30
  • 43
2

You could change the class with javascript.

$('#yourElem').click(function(){

    $(this).toggleClass('on')

})

and then manage all your transitions with css

#yourElem { background-color:red; transition: background-color 500ms ease; }

#yourElem.on { background-color:blue; }

This will transition the two on click.

Then so long as you dont out specify the hover element with the new transition you can do both.

#yourElem { color:black; background-color:red; transition: background-color 500ms ease,  color 500ms ease; }

#yourElem:hover { color:pink;  }

#yourElem.on {color:white; background-color:blue; }
Ollie
  • 646
  • 4
  • 13
  • This answer does require the jQuery javascript library, which the OP didn't indicate he wished to/could use. – cfs Aug 06 '13 at 15:34
0

you can use jquery to change the css which might help ? using on hover and the jquery colour library https://github.com/jquery/jquery-color

$('node').animate({ backgroundColor: "#f6f6f6" }, 'fast');
yckart
  • 32,460
  • 9
  • 122
  • 129