1

I am simply changing changing the color and background-color of a button when I click on it.

<input type="button" value="click me" id="myButton" onclick="ChangeColor()"/>

The CSS of this button contains CSS transition for the color and background-color, however, on the :hover pseudo-element I didn't add any styles, I didn't change the color.

#myButton{
     color:#3399FF;
     background-color:#FFFFFF;
     /* These transitions are supposed to change the color in case I hover over the button */
     -webkit-transition: background 0.5s,color 0.5s;
        -moz-transition: background 0.5s,color 0.5s;
            transition: background 0.5s,color 0.5s;
}
#myButton:hover{
     /* But since there's nothing here, the color won't change when I hover */
}

Now, when I change the styles via JavaScript, they change while using the transitions, means, the colors will change after 0.5s, and not instantly.

function ChangeColor()
{
   document.getElementById("myButton").style.color = "#FFFFFF";
   document.getElementById("myButton").style.backgroundColor = "#3399FF";
}

This is a really good thing, and I like it, but I'm just wondering, how does JavaScript respect CSS3 transitions? Is there any documentation for this?

1
  • CSS3 transitions are supported natively by the browser I thought. Commented Mar 15, 2013 at 23:47

2 Answers 2

3

Your transitions are applied whenever the value of the property is changed. It doesn't matter whether you change it on hover, focus, resize (with a media query for example), click or any other event via JavaScript.

In general, you have a transition between two states of the element. You first define the initial state:

#myButton {
     color: #39f;
     background: #fff;
     transition: .5s;
}

When you change the value of either of those two properties (and it doesn't matter whether you do this using the :hover pseudo-class or JavaScript), your element will go into another state and you are going to have a transition between the values of the properties from the initial state and those from this new state.

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

Comments

2

The method you're using to change the style with JavaScript is essentially a way of manually changing the style attribute directly on the element itself. Any time the style changes to something else and you have a transition defined for it, that transition will activate to change to the new style. That includes changes that JavaScript makes to the styles.

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.