I want to animate a translateX with transition on a click event by adding a class to the div in the js. The transform and transition properties are added in the css file.
var widget = document.getElementById('widget');
widget.style.display = 'block';
document.getElementById('widget2').clientWidth; //comment this line out and it wont work
widget.className = 'visible';
It only works if I query the width property of any element in the dom before adding the class.
here is a jsfiddle: https://jsfiddle.net/5z9fLsr5/2/
Can anyone explain why this is not working?
When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable.
The transition-property property specifies the name of the CSS property the transition effect is for (the transition effect will start when the specified CSS property changes). Tip: A transition effect could typically occur when a user hover over an element.
A transition occurs when a CSS property changes from one value to another value over a period of time. The transition property is a shorthand of four CSS properties, transition-property , transition-duration , transition-timing-function , transition-delay .
CSS3 Transition Properties Are Not Inherited (In AngularJS)
That's because you begin your transition and modified the display
property "at the same time". Altering display
will ruin any transition (citation needed, admittedly), so it would be a good idea to isolate the display
changing and actual transiting:
https://jsfiddle.net/5z9fLsr5/3/
document.getElementById('showWidget').addEventListener('click', function(e) {
e.preventDefault();
var widget = document.getElementById('widget');
widget.style.display = 'block';
//document.getElementById('widget2').clientWidth;
window.setTimeout(function(){
widget.className = 'visible';
},0);
});
#widget {
width: 200px;
height: 80px;
background: black;
position: absolute;
transition: transform 500ms;
transform: translateX(-200px);
display: none;
}
#widget.visible {
transform: translateX(200px);
}
#widget2 {
position: absolute;
right: 0
}
<a href="#" id="showWidget">show</a>
<div id="widget"></div>
<div id="widget2">xxx</div>
Querying clientWidth
seems to "pause" the execution for some time, so it works too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With