A
A
Arseniy2020-05-06 16:11:56
css
Arseniy, 2020-05-06 16:11:56

How to run script when block height changes?

The page has a floating block when scrolling and several spoilers:

<div class="container" id="js-sticky-container">
  <!-- плавающий блок-->
  <div class="sticky-block">
    <!-- какое-то седержимое плавающего блока-->
  </div>
  <div class="content">
    <div class="spoilers">
      <!-- несколько спойлеров-->
      <div class="spoilers__item">
        <div class="spoilers__item-toggle"></div>
        <div class="spoilers__item-content"></div>
      </div>
      <div class="spoilers__item">
        <div class="spoilers__item-toggle"></div>
        <div class="spoilers__item-content"></div>
      </div>
      <div class="spoilers__item">
        <div class="spoilers__item-toggle"></div>
        <div class="spoilers__item-content"></div>
      </div>
    </div>
  </div>
</div>


The task is simple, so that when the page is scrolled, the block sticks and floats - this is implemented and works, however, for the block - inside which there is a floating element, the height constantly changes due to spoilers, accordingly, you need to initialize the script for the floating block with any change in the height of the .container block.

Tried this for now:
if (document.getElementById('js-sticky-container')) {

    let target = document.getElementById('js-sticky-container');
    let $target = $(target);
    let lastHeight = $target.height();

    let observer = new MutationObserver(() => {
        let newHeight = $target.height();
        if (lastHeight !== newHeight) {
            // тут инициализируется скрипт для плавающего блока

        }
    });

    observer.observe(target, { attributes: true, subtree: true });
}


This script works partially, let's say initially when the page is loaded, the container block has a small height, so the sticky-block block does not stick when scrolling, and then the user opens one or more spoilers, then the height is already enough, the script is initialized and the block sticks, but when we collapse back all the spoilers and the height of the container again becomes insufficient for the sticky-block block to stick when scrolling, it still sticks, although it should not, that is, the script did not start again and did not recalculate its values. How can I make sure that whenever the height of the container changes, the script for the floating block is restarted?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arseny, 2020-05-06
@Arsenij00

If you don't need to change the content of the sticky block, but only recalculate it, then why didn't you use the usual position :sticky;?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question