BooFar
BooFar

Reputation: 31

JavaScript/jQuery: Monitor change to element?

Is there any way (aside from creating a new event) that I can tell when a particular CSS class has been added to an element?

Upvotes: 3

Views: 1611

Answers (3)

user113716
user113716

Reputation: 322502

If you don't have access to the code that's adding the class, there's a jQuery plugin called livequery that will allow you to run code when elements are added to the DOM (or when you do things like add a class to an element).

http://brandonaaron.net/code/livequery/docs

$('div.myClass').livequery(function() {
     alert('myClass was added');
});

$('#someDiv').addClass("myClass");  // The livequery code will run

This works specifically with jQuery methods.

Upvotes: 4

Sam Day
Sam Day

Reputation: 1719

There is a DOM Level 3 specification to detect changes to an elements attributes, it is supported in a couple of browsers... Also IE supports an onpropertychange (http://msdn.microsoft.com/en-us/library/ms536956(VS.85).aspx) event too.

It's probably not going to be enough though. Your best bet is use window.setInterval() and check if the value has changed.

Upvotes: 0

alex
alex

Reputation: 490283

You could extend jQuery's addClass() to fire an event when it adds a class. However, this means you'll have to add classes always with this method.

If you don't do that, you'll have to poll and look for differences in the class attribute. I don't recommend doing that. Besides performance, you'll need to handle classes being removed too.

Upvotes: 0

Related Questions