2

I am building a simple JQuery widget. My widget builds appends a few items. I would like to know how to properly add event-functions to these newly added items from within the widget.

For example:

(function ($) {
    $.widget('be.tagEditor', {
        options: {
        },
        _init: function () {
            var me = this;
            createObj();
        },
        createObj: function() {
            var me =this,
                obj = me.element;
            obj.append('<div class="example">');
        }
    });
})(jQuery);

If I had something like the above, what would be the proper way to add events to the div?

2 Answers 2

3

The most efficient method is to use jQuery's .on() event binding. For example:

$(document).on('click', '.example', function () { ... });

You can define that anywhere in your code and it will fire when an element with that class (here example) has the appropriate trigger (here click).

This is more efficient than adding event handlers to each item as it is created, especially when the number of elements is potentially large.

Note: Earlier versions of jQuery had a .live() method to achieve this, which got removed in version 1.9. The equivalent to the code above in those versions would look like this:

$('.example').live('click', function () { ... });
Sign up to request clarification or add additional context in comments.

2 Comments

Note if you do the above you must ensure the elements do not already have a live binding otherwise you will add a duplicate event
Right, this should go somewhere in the outer scope of the program, not inside a loop.
0

I'd suggest to pass in an object literal to the jQuery contructor. That object can take anything you want. For instance:

obj.append('<div>', {
    'class':    'example',
    text:       'foobar!',
    click:      function(e) {
         alert('I was clicked!');
    }, 
    mouseenter: function(e) {
         alert('mouse hovered me, oh no!');
    },
    css:  {
        backgroundColor:  'red'
    }
});

You can add every event handler to that object literal jQuery can handle. In the above example it's adding a click and mouseenter event along with setting the text-content, the CSS class and a CSS property via css. To learn more about this have look at http://api.jquery.com/jQuery/ or, explained in more detail, at http://typeofnan.blogspot.com/2011/02/did-you-know.html.

1 Comment

Thank you for this, I will definitely look into this more, but for the current, Liza's response works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.