G
G
Golopolos2021-06-27 20:03:52
JavaScript
Golopolos, 2021-06-27 20:03:52

Hidden block appears for a second on page refresh?

There is a block that is collapsed and a cookie hangs on it. When the page is refreshed, it expands for a second and collapses back. How to remove it?

function closed() {
    let html = document.querySelector('body');
    window.addEventListener('unload', () => {
      setCookie('closed', html.classList.contains('closed') ? 1 : 0);
    });
    if (getCookie('closed') == 1) {
      html.classList.add("closed");
    }
    document.querySelector('.block').addEventListener('click', function() {
      html.classList.toggle("closed");
    });
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2021-06-27
@Golopolos

When the page is refreshed, it expands for a second and collapses back. How to remove it?
Well, since your element does not have the closed class until the function is executed, it is logical that it is loaded open.
How to remove it?
1) add the closed element in the code, and remove it when the function is called, if the cookie contains the required flag. There will also be a delay, but already at the opening, which is not so scary.
2) On the server side, check the cookie, and add the required class to the markup on the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question