views:

45

answers:

3

I need to execute a JQuery code when an element's class attribute is changed. For example, initially the element will be : <div class="my-class">. So, when a new class is added to this div, (i.e. <div class="my-class new-class">, I have to trigger a JQuery code.

How do I do this in JQuery? Is there event for attribute change?

A: 

Cant' you just bind the functionality to the function that changes the class?

meder
I can't. Because the CSS attribute is changed by an external JS function on which I don't have any control.
Veera
How external? Can you provide more info?
meder
I'm trying to enhance the SERPs that Google CSE returns. So, in this case, Google's JS is modifying the element's attributes. When they modify an attribute, I need to call my JS.
Veera
A: 

There is no cross browser node changed event.

One option could be to use the LiveQuery plugin. It will scan the dom periodically looking for changes and will raise an event if it encounters a change.

redsquare
+1  A: 

If you have absolutely no means of telling when the external function changes the class (like, a custom event, for example), you will have to do something like this:

$(document).ready(function(){

    // Cache the required element
    window.elementInQuestion = $('#element-that-changes-class');

    function checkClass(){
        if (window.elementInQuestion.hasClass('new-class')) {
            // Trigger a custom event
            $(document).trigger('elementHasClass');

            // If you need the check only until the first time the class appears
            // you can cancel further checks here
            clearInterval(window.classCheckerInterval);
        }
    }

    // Check if an element has class every once in a while
    window.classCheckerInterval = setInterval(checkClass, 100);

    $(document).bind('elementHasClass', function(){
        // Your handler here
    });
});
Igor Zinov'yev
the solution worked. but the line if (window.elementInQuestion.hasClass('new-class')) only works when I change it to if ($('#element-that-changes-class').hasClass('new-class'))
Veera