Veera
Veera

Reputation: 33172

Jquery event for changing an element's class attribute

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?

Upvotes: 1

Views: 1857

Answers (3)

Igor Zinov&#39;yev
Igor Zinov&#39;yev

Reputation: 3706

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
    });
});

Upvotes: 2

redsquare
redsquare

Reputation: 78667

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.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186562

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

Upvotes: 0

Related Questions