cmplieger
cmplieger

Reputation: 7371

How to determin that javascript has finished doing something

JS on ios is rather slow. For example in this piece of code, the Js adds the class before being able to add the block style. This breaks an animation i have on the page.

comments.style.display="block";comments.className = "show";

I have a workaround that fixes the issue on ios but just feels wrong:

comments.style.display="block";setTimeout(function(){comments.className = "show";},1)

Is there any way to determine if the block style has been set and only then trigger the second part?

Thanks for your suggestions!

Upvotes: 0

Views: 99

Answers (2)

davidbuzatto
davidbuzatto

Reputation: 9444

Can't you just use an if?

<div id="foo" style="display: none;">foo</div>

var div = document.getElementById( "foo"  );
if ( div.style.display == "none" ) {
    div.style.display = "block";
}

If you want to listen to a class change (or a style change) "event", you can try these links:

I think the first one will solve your problem. Here is the code:

document.documentElement.addEventListener( "DOMAttrModified", function( evt ){
    if ( evt.attrName === "style" ) {
        if ( evt.newValue.indexOf( "block" ) != -1 ) {
            alert( "do something!" );
        }
    }
}, false );

document.getElementById( "foo" ).style.display = "block";

Upvotes: 1

user266647
user266647

Reputation:

This is a glorious mess of a hack that may work:

comments.blockStyleEvent = function() {
   if ( this.style.display === "block" ) {
      this.onBlockStyleEvent.apply(this);
   }
};

comments.onBlockStyleEvent = function() {
   this.className = "show";
};

setInterval(function(){
  comments.blockStyleEvent();
}, 1);

You could also create two css classes one show and another showAsBlock for example then you could do this:

// somewhere else
comments.className = "hide";

// ...then
comments.className = "showAsBlock";

Upvotes: 1

Related Questions