Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically call jQuery functions on new dom elements

Is it possible to call an jQuery function on newly matched items automatically?

For example I have the following code:

$(document).ready(function(){
    $('[draggable]').draggable();
});

This adds the 'draggable' to each element which matches [draggable] however when further along the road new elements with the attribute 'draggable' are added those are not getting the 'draggable()' function getting called on them.

Is it possible to monitor the DOM or something and also call this method on each new dom item which matches the selector?

I know there is something like this for 'click' events and such (the jquery delegate method) but as far as I know I can't seem to use that for this case.

like image 602
Matthijn Avatar asked Aug 26 '12 20:08

Matthijn


People also ask

How do you call a function automatically?

In order to run a function automatically after waiting for some time, we are using the jQuery delay() method. The . delay() method in jQuery which is used to set a timer to delay the execution of the next item in the queue.

Which method is triggered when an element is added to the DOM?

We can detect if an element has been added to DOM using the MutationObserver object. This provides the ability to observe for changes being made to the DOM tree.

How to use ready function in jQuery?

$( document ).ready() A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.


3 Answers

Check "Mutation Events" there is an event called DOMNodeInserted maybe it helps you

by the way, check: JQuery - use element with DOMNodeInserted

like image 142
Mario Corchero Avatar answered Oct 13 '22 05:10

Mario Corchero


You can use the arrive.js library that I developed for the exact same purpose (it uses MutationObserver internally). Usage:

document.arrive('[draggable]', function(){
    // 'this' refers to the newly created element
    $(this).draggable();
});
like image 32
Uzair Farooq Avatar answered Oct 13 '22 05:10

Uzair Farooq


there was ".live()" for jQuery, but i see it's deprecated?! don't get the transformation from ".live()" to the new ".on()"-method currently, but take a look @ yourself and maybe ask in their forum... this should be the right way to do...

http://api.jquery.com/live/

like image 22
TheHe Avatar answered Oct 13 '22 05:10

TheHe