Javascript event on CSS style change from block to none

13,219

Solution 1

There are no DOM events triggered for visibility changes.

The best you can do is always use the same function to adjust the block's visibility instead of changing it's style each time.

Old pattern:

function doSomething() {
    alert("I'm doing something!");
    myBlock.style.display = "block";
}

function doSomethingElse() {
    alert("I'm doing something else now!");
    myBlock.style.display = "none";
}

New pattern:

function doSomething() {
    alert("I'm doing something!");
    toggleMyBlock(true);
}

function doSomethingElse() {
    alert("I'm doing something else now!");
    toggleMyBlock(false);
}

function toggleMyBlock(show) {
    if (show) {
        // code here for what would be your 'it became visible' event.
    } else {
        // code here for what would be your 'it became invisible' event.
    }
    myBlock.style.display = show ? "block" : "none";
}

Solution 2

Going forward, the new "Intersection Observer API" is what you're looking for. It currently works in latest Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.

Simple code example for observing display:none switching:

// Start observing visbility of element. On change, the
//   the callback is called with Boolean visibility as
//   argument:

respondToVisibility(element, callback) {
  var options = {
    root: document.documentElement
  }

  var observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      callback(entry.intersectionRatio > 0);
    });
  }, options);

  observer.observe(element);
}

respondToVisibility(myElement, isVisible => {
  if (isVisible) {
    doSomething();
  }
});

In action: https://jsfiddle.net/elmarj/u35tez5n/5/

Solution 3

You could use JavaScript to listen to a DOM event for a CSS3 transition (with a minimal fade time):

Solution 4

I think the closest to what you're looking for would be the DOMAttrModified event. I'm not entirely sure on it's usage, but it's along the lines of:

element.addEventListener('DOMAttrModified', function (e) {
  ...
});

The event handler receives a MutationEvent which should provide you enough information to determine whether display has been set to block or none.

EDIT

I may have misread the question. I don't believe a CSS change will result in a DOMAttrModified event. Initially, I had read the question to mean you were setting display with a CSS value via JavaScript. My answer may not be helpful.

Share:
13,219
curioussam
Author by

curioussam

Updated on June 17, 2022

Comments

  • curioussam
    curioussam almost 2 years

    Is there a pure Javascript event (no jQuery) that is fired when I change the CSS style of my div from block to none. I was under the impression I can catch that via "onBlur" but looks like I cannot!

    Please advise!