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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm a newbie and didn't realize I could change classes on the fly.
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; }

1 Comment

This answer does require the jQuery javascript library, which the OP didn't indicate he wished to/could use.
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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.