I need to apply a jQuery plugin to an HTML element that will be created upon a user's input. For example:
<!-- Upon click, this link creates a new div with an id of 'target'. -->
<a id="trigger-a" href="javascript:void(0);">Create a new div</a>
/* This will not work because div#target isn't available yet upon page load. */
$(function() {
$("div#target").aJQueryPlugin( ... );
});
In the simplest form, I can call the plugin inside the <a>
's click handler, after the div is created.
$(function() {
$("#trigger-a").click(function() {
// Create div#target.
// I can call the plugin here but is there a different, maybe better, way?
$("div#target").aJQueryPlugin( ... );
});
});
However, if possible, I am looking for something that is more "automatic"; maybe using .on()
that automatically invokes the plugin once the element becomes available?
Paraphrasing the question: In jQuery, is there a way to "monitor" when a certain element becomes available (i.e. after it's being created)? If there is, I'd then call the plugin or other functions as a callback.
Maybe something like this?
<a id="trigger-a" href="javascript:void(0);">Create a new div</a>
<div class="cont"></div>
$("#trigger-a").click(function () {
var $div = $('<div>', {class: 'target', text: 'text'});
$('.cont').append($div);
$div.trigger('divCreate');
});
$('.cont').on('divCreate', 'div.target', function () {
$(this).append('added by event')
});
http://jsfiddle.net/Q2UYC/
Triggering custom event let you bind event handler later.
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