1

I have a form in my webpage which submits info to an external app and changes the style of an element based on the response from "display:none" to "display:block".

I want to be able to run a function once that change has been made, as it's my indication that the operation was successful.

How would you do such a thing?

Geva Tal
  • 340
  • 3
  • 14

1 Answers1

1

Here's a quick and dirty way of doing it:

var onElementStyleChange = (function() {
  var elements = [],
      started = false;
  return function(element, callback) {
    elements.unshift({element: element, callback: callback});
    if (!started) {
      window.setTimeout(function checkElements() {
        for (var i = elements.length - 1; i >= 0; i--) {
          var element = elements[i].element,
              callback = elements[i].callback;
          if (element.style.display === 'block') {
            callback();
            elements.splice(i,1);
          }
        }
        if (elements.length) {
          window.setTimeout(checkElements, 0);
        } else {
          started = false;
        }
      },0);
      started = true;
    }      
  }
}());

then you can call this do have it check your element:

onElementStyleChange(element, function() {
  //do stuff..
});

Explanation: onElementStyleChange keeps checking your element over and over again and doesn't stop checking until your element's display style property is block. Once it sees that your element has display: block, it calls whatever function you pass into it and stops checking.

EDIT: Updated so that any number of elements can use this function.

Daniel Weiner
  • 1,874
  • 12
  • 19