Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
Why isn't my CSS transition applying when I change the element's style through JavaScript?
Asked on Dec 22, 2025
Answer
When CSS transitions don't apply, it is often due to how styles are being updated. Ensure that the transition properties are defined in the CSS and that the style changes trigger the transition.
<!-- BEGIN COPY / PASTE -->
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: background-color 0.5s ease;
}
</style>
<div class="box" id="box"></div>
<script>
const box = document.getElementById('box');
box.addEventListener('click', () => {
box.style.backgroundColor = 'red';
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Ensure the CSS transition is defined in the stylesheet, not dynamically via JavaScript.
- The transition property should specify which CSS properties to animate and the duration.
- The JavaScript code should change the style property that is specified in the transition.
- In this example, clicking the box changes its background color, triggering the transition effect.
Recommended Links:
