Issue
Often fade in/out animations seem to be trickier then they should be because you also have to time display:none to toggle at the right moments.
Is there a downside to toggling pointer-events: none instead of display: none?
Assume the element is absolutely positioned, so we're not worrying about it taking up space.
Example code showing a fade animation using pointer-events instead of display: none.
function animate(e) {
document.body.querySelector('p').className = 'animate'
}
p {
opacity: 0;
pointer-events: none;
transition: opacity 500ms;
}
p.animate {
opacity: 1;
pointer-events: unset;
}
<button onclick='window.animate()'>Clicky!</button>
<p>Hi there</p>
Solution
As you already hinted, the downside, compared to display: none;
, is that only pointer-events are disabled. The element is still there in rendered output and selectable, be it may with something else than a pointer.
pointer-events: none;
won't prevent from focusing an element using the TAB
key, for instance.
For all non-interactive elements such as overlay-screens etc. it shouldn't be an issue. But for any element with which can be or should be interacted, I wouldn't use pointer-events
to control whether the element is interactive, as it simply only covers one use-case: that of a pointer.
I tend to opt for adding a listener for animationend
or transitionend
to animate something with CSS and after the animation setting the display
to none
:
function animate(_e) {
_e.currentTarget.passEffectOn.classList.add('animate');
}
function animationEnd(_e) {
_e.target.style.display = 'none';
_e.target.passOn.classList.add('animate');
}
const myButton = document.getElementById('myButton');
const myParagraph = document.getElementById('myParagraph');
const theirParagraph = document.getElementById('theirParagraph');
myButton.passEffectOn = myParagraph;
myParagraph.passOn = theirParagraph;
myButton.addEventListener('click', animate);
myButton.passEffectOn.addEventListener('transitionend', animationEnd);
#myParagraph {
opacity: 1;
transition: opacity 500ms;
}
#myParagraph.animate {
opacity: 0;
}
#theirParagraph {
opacity: 0;
transition: opacity 500ms;
}
#theirParagraph.animate {
opacity: 1;
}
<button id="myButton">Clicky!</button>
<p id="myParagraph">Hi there</p>
<p id="theirParagraph">The other is <code>display: none;</code></p>
Answered By - Martijn de Heer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.