This can happen because the change in class causes the element's dimensions to change, which in turn affects the layout of the page. To prevent this flickering effect, it's best to add the CSS class before the offsetHeight property is accessed.
One way to do this is to use a setTimeout function to delay the offsetHeight property call. For example:
const el = document.querySelector('.my-element');
el.classList.add('my-class');
setTimeout(() => {
const height = el.offsetHeight;
// do something with the height
}, 0);
By adding the class first and then waiting for a small delay before accessing offsetHeight, the element's dimensions will be settled and the resulting layout change won't cause flickering.
Asked: 2021-04-29 11:00:00 +0000
Seen: 7 times
Last updated: Sep 23 '22