Oct 6, 2010
Detect Attribute Changes with jQuery
Posted in "development"
Update: Since first publishing this article in 2010, there was a Mutation Observer specification that came about and is now incorporated into my
$.watch() plugin. The latest code can be found over on Github at https://github.com/darcyclarke/jQuery-Watch-Plugin
This is, in large part, a very easy problem to solve, without a DOM event, using a recursive check of my element utilizing
setInterval(). The problem with this solution is it's sheer bloat and constant DOM traversing to check my selected element's attributes every second. So, in light of this solutions pitfalls, we can use a little known DOM event called DOMAttrModified (you can read more about this and all other standard DOM events here: http://www.w3.org/TR/DOM-Level-2-Events/events.html)
The Best Solution
This event is not commonly used most likely because it is not yet supported by all browsers. That said, IE does support a similar event called
propertychange, and, at the very least, we can always fall back on our initial
setInterval() solution if we're dealing with all other browsers that don't support anything (I'm looking at you Chrome/Safari). You can see a list of browsers and event compatibility here: http://www.quirksmode.org/dom/events/index.html
This plugin lets you specify which attributes to "watch" for changes. It will fire your callback function when one of the attributes has changed.
<iframe width="100%" height="400" src="http://jsfiddle.net/darcyclarke/V6asr/9/embedded/result,js,html,css" allowfullscreen="allowfullscreen" frameborder="0"></iframe>