1

I have a slide up / down div. Because you cannot have it slide up out of view with just CSS, I'm instead using JavaScript like this:

showHideElement = (element, open) => {
  if (open) {
    element.style['margin-top'] = 0;
  } else {
    element.style['margin-top'] = -element.scrollHeight + "px";
  }
}

I then have a button that the user can click to toggle the div in or out of view. This all works fine.

The problem is that I want to be able to save the user's preference, such that if they toggle the div out of view, the next time they refresh the page it is already toggled out of view. This is done using localstorage.

The issue I'm having is that in order to determine the margin-top, the element has to first be rendered, so that its scrollHeight can be found. This is causing a "flash" when the user refreshes the page, wherein they see the div for a moment slide out of view.

I desire a solution where the div is already out of view when the user loads the page, but how can that be determined without first rendering it to determine the scrollHeight so that its margin-top can be set?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136

2 Answers2

1

You need to calculate element height, which is possible by rendering element.

You can try visibility: hidden with position: absolute. It won't create a white rectangle.

When rendering is done. You can reset position e.g position: unset (or default value).

harish kumar
  • 1,732
  • 1
  • 10
  • 21
0

try setting it to display:none or visibility: hidden

lizzors
  • 29
  • 7
  • `display: none` doesn't work because then the measured height (scrollHeight) is 0. `visibility: hidden` doesn't work because then it's instead a white rectangle that is flashed instead. – Ryan Peschel Jun 17 '20 at 16:44
  • `visibility:hidden; opacity: 0` instead – Tyr Jun 17 '20 at 17:06