2

Is there some sort of on render function in jQuery. I'd like this function to get triggered whenever a new element with the specified class or ID is added on the screen, either on the page load, or after AJAX requests that return HTML.

Edit: I want a callback that fires whenever a new element with the class or ID that I've defined is created. Not when something changes. I'd prefer not to use a plugin.

mas-designs
  • 7,498
  • 1
  • 31
  • 56
Jeffrey
  • 1,985
  • 1
  • 12
  • 21

4 Answers4

0

mmmmm.....

My Advice :

Create a Factory function of Creation of elements .

Every time you want to create an element ,

pass it through a centrelized function WHICH create the element.

She will have prameter of "what to create"

and she will create it.

then , put your code for "after creating element" in the same func

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

I'm solving it this way:

$('html').change(function() {
    $('.element').each(function() {
        // Do stuff.
    });
});

This way I can have an array that keeps track of all my elements, and when a HTML change is triggered check if there are elements that are not in my array, thus new elements.

david
  • 3,225
  • 9
  • 30
  • 43
Jeffrey
  • 1,985
  • 1
  • 12
  • 21
  • You may want to implement the observer pattern http://addyosmani.com/blog/understanding-the-publishsubscribe-pattern-for-greater-javascript-scalability/ – Gabo Esquivel Feb 16 '12 at 14:39
0

There is a new event for that but as usual it won't work for < IE9:

<head>
    <script type="text/javascript">
    function AddTextToContainer () {
        var textNode = document.createTextNode ("My text");
        if (textNode.addEventListener) {
            textNode.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
        }

        var container = document.getElementById ("container");
        container.appendChild (textNode);
    }

    function OnNodeInserted (event) {
        var textNode = event.target;
        alert ("The text node '" + textNode.data + "' has been added to an element.");
    }
    </script>
</head>
<body>
    <div id="container" style="background-color:#e0d0a0; width:300px; height:100px;"></div>
    <br /><br />
    <button onclick="AddTextToContainer ();">Add a text node to the container!</button>
</body>
Asken
  • 7,679
  • 10
  • 45
  • 77
  • Actually... seems it's also been deprecated. Strange since IE9 just got it :). Read the warning label. http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted – Asken Feb 16 '12 at 14:38
-1
$(document).on('DOMSubtreeModified',function(){
    // something changed
});

Maybe this works for you but I'm not sure if every browser supports this event. EDIT: Even this event is deprecated. So you should not use it. Quick overview about events available:

mas-designs
  • 7,498
  • 1
  • 31
  • 56