JS_is_awesome18
JS_is_awesome18

Reputation: 1757

How to apply my jQuery plugin to dynamically created elements

I am building an app that dynamically generates section elements styled as post it notes. I am configuring this app to take the form of a jQuery plugin. The function to generate the sections works fine, but I am unable to render my default plugin styling options onto the sections. Basically, my plugin does not seem to apply to my dynamically created elements. Any recommendations on how to fix this? See Code below. Thanks!

index.html

    <div id="mylist"></div>

    <input type="button" id="NewElement" value="New Element">

    <script src="script.js"></script>

    <script>
      $("section").newNote();
    </script>
script.js

(function ( $ ) {
$.fn.newNote = function(options) {

    $('#NewElement').on('click',function(){
        $('#mylist').append("<section></section><br />");
    });

        var settings = $.extend({
            radius: 3,
            border: 0,
            background: "linear-gradient(#f9efaf, #f7e98d)",
            resize: "none",
            width: "20%",
            padding: 20,
            overflow: "hidden",
            height: 200,
            margin: "1%",
            float: "left"
        }, options );

        return this.css({
            radius: settings.radius,
            background: settings.background,
            resize: settings.resize,
            width: settings.width,
            padding: settings.padding,
            overflow: settings.overflow,
            height: settings.height,
            margin: settings.margin,
            float: settings.float
        });
};
}( jQuery ));

Upvotes: 0

Views: 183

Answers (1)

Abhishek
Abhishek

Reputation: 1006

Update your method as shown in below code snippet

(function ( $ ) {

 $(document).on('click', '#NewElement', function () {
        $('#mylist').append("<section></section><br />");
        $('section').newNote();
 });

$.fn.newNote = function(options) {
        var settings = $.extend({
            radius: 3,
            border: 0,
            background: "linear-gradient(#f9efaf, #f7e98d)",
            resize: "none",
            width: "20%",
            padding: 20,
            overflow: "hidden",
            height: 200,
            margin: "1%",
            float: "left"
        }, options );

        return this.css({
            radius: settings.radius,
            background: settings.background,
            resize: settings.resize,
            width: settings.width,
            padding: settings.padding,
            overflow: settings.overflow,
            height: settings.height,
            margin: settings.margin,
            float: settings.float
        });
};
}( jQuery ));
<div id="mylist"></div>
<input type="button" id="NewElement" value="New Element">
<script src="script.js"></script>

Upvotes: 1

Related Questions