kylex
kylex

Reputation: 14406

jQuery plugin: get events to fire only on the element acted upon

I'm attempting to create a plugin, but am having issues with multiple instances. I want the code to ONLY act on the instance that is being used, but currently, if I click on one, it acts on both. How do I write a plugin that only acts on the instance I am interacting with? Below is a stripped down sample of what I'm talking about.

(function( $ ) {
    $.fn.cals = function(options) {
    var containing_element = this;


        var opts = $.extend( {}, options);

        // create a container after each element
        $(containing_element).after('<div class="container">Click</div>');

        return this.each(function() { 
             $('.container').on('click', function() { 
                  console.log('test')
             })
        }); // END this.each
    };
})( jQuery );

The html code is:

<script>
    $(document).ready(function() {
        $('.test').cals();
    });
</script>

    <div class="test" type="text">
    <div class="test" type="text">

</html> 

The code inserts <div class="container>Click</div> below both .test divs. When I click on one, console.log('test') spits out 2 "test". I only want the code to act on the instance I'm interacting with.

Upvotes: 0

Views: 138

Answers (1)

David Thomas
David Thomas

Reputation: 253506

I'd suggest amending your plugin syntax to append the new element (in this case a clone of the element previously-defined) in the each() loop:

(function ($) {
    $.fn.cals = function (options) {
        var containing_element = this;
        var opts = $.extend({}, options);

        // create containing element for calendar
        var container = $('<div />', {
            'class' : 'container',
            'text' : 'click',
            'click' : function(){
                console.log('test');
            }
        });

        return this.each(function () {
            $(this).after(container.clone(true, true));
        }); // END this.each
    };
})(jQuery);

JS Fiddle demo.

Incidentally, containing_element is already a jQuery object (as is the this within the scope of the function, albeit not within the each()), it didn't need to be re-wrapped in jQuery, although it does no harm to do so, but it's needlessly expensive.

Upvotes: 1

Related Questions