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.
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.
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.
$( 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.
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.
Check "Mutation Events" there is an event called DOMNodeInserted maybe it helps you
by the way, check: JQuery - use element with DOMNodeInserted
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();
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With