Darcy Clarkebuilding products / experiences / communities & culture

Toggle Main Navigation

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

The Problem

One of the biggest issues I've come across, in my recent run in's with event driven Javascript programming, is tracking attribute changes in the DOM. A good example of what I'm talking about would be: When my <p> tag has it's background color changed to red. Usually, the only way you could track this change would be to trigger an event when you go to change that background color. This isn't very scalable as you would have to bind every animation you create with some sort of trigger. Instead, what I'm looking for, is a DOM event to be thrown when this change happens.

A Solution

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

Since jQuery is a defacto go-to Javascript Library for developers these days, I created a plugin for it which mimics the DOMAttrModified event across all browsers.

Description:

This plugin lets you specify which attributes to "watch" for changes. It will fire your callback function when one of the attributes has changed.

Demo:

http://darcyclarke.me/dev/watch/

<iframe width="100%" height="400" src="http://jsfiddle.net/darcyclarke/V6asr/9/embedded/result,js,html,css" allowfullscreen="allowfullscreen" frameborder="0"></iframe>