How can I call a function every time the DOM changes in jQuery?

I need to make sure the page remains as my script describes even after changing the DOM; my script must handle these changes in the DOM, so my script does not only handle the initial state.

Is there some kind of event that I can use to handle these DOM changes?

+5
source share
2 answers

Taking your question in the strict sense of the word is something like this:

//--- Narrow the container down AMAP.
$("YOUR SELECTOR").bind ("DOMSubtreeModified", HandleDOM_ChangeWithDelay);

var zGbl_DOM_ChangeTimer = null;

function HandleDOM_ChangeWithDelay (zEvent) {
    if (typeof zGbl_DOM_ChangeTimer == "number") {
        clearTimeout (zGbl_DOM_ChangeTimer);
        zGbl_DOM_ChangeTimer = '';
    }
    zGbl_DOM_ChangeTimer     = setTimeout (HandleDOM_Change, 333);
}

function HandleDOM_Change () {
    // YOUR CODE HERE.
}

Please note that you want an intermediate delay function because the changes will be in clusters of 10 to 100 events on a site such as Youtube or Google.

- , , .



:

, DOMSubtreeModified, . , , .

, Raynos, . , Firefox .

: script , , script /.

, ( ):

function HandleDOM_Change () {
    // YOUR CODE HERE.
}

//--- Narrow the container down AMAP.
fireOnDomChange ('YOUR JQUERY SELECTOR', HandleDOM_Change, 100);

function fireOnDomChange (selector, actionFunction, delay)
{
    $(selector).bind ('DOMSubtreeModified', fireOnDelay);

    function fireOnDelay () {
        if (typeof this.Timer == "number") {
            clearTimeout (this.Timer);
        }
        this.Timer  = setTimeout (  function() { fireActionFunction (); },
                                    delay ? delay : 333
                                 );
    }

    function fireActionFunction () {
        $(selector).unbind ('DOMSubtreeModified', fireOnDelay);
        actionFunction ();
        $(selector).bind ('DOMSubtreeModified', fireOnDelay);
    }
}
+13

DOM, document.ready, . on() . live() , , .

0

All Articles