Reputation: 2112
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?
Upvotes: 2
Views: 1726
Reputation: 2963
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 () { ... });
Upvotes: 3
Reputation: 235962
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.
Upvotes: 0