I want to execute a function when some div or input are added to the html. Is this possible?
For example, a text input is added, then the function should be called.
I want to execute a function when some div or input are added to the html. Is this possible?
For example, a text input is added, then the function should be called.
How about extending a jquery for this?
Jquery 1.9+ has built support for this(I have heard not tested).
Use JQuery MutationObserver as shown in Gabriele Romanato's blog
Chrome 18+, Firefox 14+, IE 11+, Safari 6+
I have recently written a plugin that does exactly that - jquery.initialize
You use it the same way as
.each
functionThe difference from
.each
is - it takes your selector, in this case.some-element
and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:
Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then
.detach()
it from body and then add it again, it will not be initialized again.Plugin is based on
MutationObserver
- it will work on IE9 and 10 with dependencies as detailed on the readme page.or you can simply Create your own event, that run everywhere
Full example http://jsfiddle.net/hbmaam/Mq7NX/
This is an example using MutationObserver from Mozilla adapted from this blog post
Chrome 18+, Firefox 14+, IE 11+, Safari 6+
This is the ultimate approach so far, with smallest code:
IE9+, FF, Webkit: