I have a little problem understanding the event handling of the jQuery Ui Widget factory.
See this snipped:
$(function () {
$.widget("custom.superduper", {
_create: function () {
this._on($(this.element, "a"), {
click: function (event) {
console.log($(event.target));
}
});
}
});
$("#gallery").superduper();
});
Running on this HTML:
<ul id="gallery">
<li><a href="#"><img src="http://www.placehold.it/50x50" /></a></li>
<li><a href="#"><img src="http://www.placehold.it/50x50" /></a></li>
<li><a href="#"><img src="http://www.placehold.it/50x50" /></a></li>
</ul>
Working demo: http://jsfiddle.net/ech2htrt/2/
When you click on an image in the gallery, the console output is:
Object[img 50x50]
I expected it to be the <a>
element inside of the gallery. Of course I could use closest()
or parent()
to get the desired element, but that feels rather unnaturally. Where did I go wrong in the definition of the event handler?
Is there a better way to get the event triggering element? When i use this
or $(this)
the reference is always the widget element.
As i understand, this._on($(this.element, "a"), {
....
here you want to attach click event on anchor tag and the context should be this.element . If so the arguments are misplaced.The correct order is-
this._on($("a" , this.element), {
By doing this ,if i debug and see the event object ,i can see that the event.currentTarget is a and event.delegatetarget is also a. But as the img tag in above the anchor tag (z-index) the event.target comes out to be img.
If i increase the height and width on the anchor tag allowing me to click it arround the img tag , i get the desired results.