views:

1329

answers:

3

Is there a way to detect if the "display" css property of an element is changed (to whether none or block or inline-block...)? if not, any plugin? Thanks

A: 

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

Colin
I have several events that can trigger a box to appear or not. And I have another element that kinda depends on the appearance of that box to do things. Now, I don't want to repeat code and hook up to all other events making appearance to the box although that is one way to do it. Just redundance!
HP
It is redundant, maybe using a rule based system would work? ie, some JSON like structure that defines what should happen to some control when another control changes? this way you would only need to create 1 function tht uses the rule object and perhaps the current control(id) as parameter?
Colin
A: 

You can use jQuery's css function to test the CSS properties, eg. if ($('node').css('display') == 'block').

Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.

Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.

Not sure if this is what you're looking for.

ndp
How do you do this?
crosenblum
+7  A: 

Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.

Try something along these lines:

document.documentElement.addEventListener('DOMAttrModified', function(e){
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

document.documentElement.style.display = 'block';

You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified. It should allow to detect style changes reliably.

kangax
Thanks. Will it support Firefox ?
HP
Yes, IIRC, FF2 and up to a current one.
kangax
This won't work if the effective CSS display property for an element is changed indirectly; for example, by changing the CSS class of the element.
Tim Down