Search code examples
javascriptjqueryhtmljquery-pluginsspectrumjs

How to initialize a JQuery plugin for elements added dynamically


In this JSFiddle, I have two table.inner-table elements which were added initially in the HTML. Spectrum plugin works fine for all of the input.basic elements, that is clicking the element opens the color picker window.

BUT this JSFiddle initially has only one table.inner-table element in the HTML. When you click the button labelled Click, another table.inner-table is added. The problem is with both the input.basic elements in this newly added table. Clicking them does not open the color picker window.

I am suspecting because color picker is already initialized, so it is not working for dynamically added elements. In the JS, the plugin is initialized like this:

$(".basic").spectrum();

The question is how do I make it work for dynamically added elements?

WHAT I TRIED:

I saw this question, and added the following to JS. Did not work =(

$('body').on('focus', '.basic', function() {
    $(this).spectrum({});
});

Solution

  • var table = $('.outer-table > tbody > tr:last').clone();
    $(table).find('.sp-replacer').remove();
    $('.outer-table > tbody').append(table);
    $(".basic").spectrum({});
    

    If you click button, it would re-initialize $(".basic").spectrum({});.

    Here's a fiddle