Ask Your Question
2

The act of adding a CSS class through Javascript's offsetHeight is resulting in a flickering effect on the elements.

asked 2021-04-29 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-09-23 08:00:00 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-29 11:00:00 +0000

Seen: 7 times

Last updated: Sep 23 '22