Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Invoke a jQuery Plugin on a Dynamically-Created Element

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.

like image 613
moey Avatar asked Jan 15 '12 16:01

moey


1 Answers

Maybe something like this?

HTML

<a id="trigger-a" href="javascript:void(0);">Create a new div</a>

<div class="cont"></div>

JS

$("#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.

like image 200
ogur Avatar answered Oct 11 '22 17:10

ogur