1

Possible Duplicate:
Is there a jQuery DOM change listener?
How do can watch DOM Object properties?

Is there a way to bind events to non-input-type elements? For example, binding an event to an anchor element that fires when the href attribute is changed.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
James Jones
  • 8,653
  • 6
  • 34
  • 46

3 Answers3

3

You can bind handlers to all kinds of events on non-input elements (click, mousemove, etc.). But there is no (consistent cross-browser) event raised when an attribute changes (such as your example of an href attribute on a link). Some attributes (like src) will cause an event (like load) as a secondary thing, as bfavarello pointed out.

(There's a now-dead proposal for "mutation" events on elements, including attribute changes [mutations], but it was never broadly supported. There's a newer proposal, but it is also not [yet] broadly supported.)

You can, of course, use polling: Save the old value, and check back periodically (via setTimeout or setInterval) to see if it has changed. Unless you're checking a lot of elements and need to check them near-constantly, this needn't be a performance problem.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

DOM Mutation Observers can do this, but they're very new and not well supported at the time of writing.

Are you writing an extension or similar (ie, you don't control that code that's modifying the DOM)? That's one of the more common use cases for these events - where you don't control the code that's changing the DOM. I've used this before with the Mutation Summary which has worked well in Chrome.

If you do control the code that's modifying the DOM - ie you're modifying the attribute yourself on your own web site - you might wish to simply fire off a custom event of your own when you modify the attribute.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
1

You could add a DomSubtreeModified listener to an ancestor, or you could use watch on the src property of the DOM object if it is supported in the browser you are using.

myImage.watch("src",function(id, oldval, newval){
    document.write("src changed!");
    return newval;    
});
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139