Nico O
Nico O

Reputation: 14152

jQuery UI widget factory _on event returns unexpected event target

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.

Upvotes: 0

Views: 229

Answers (2)

Abhishek Nafdey
Abhishek Nafdey

Reputation: 106

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.

Upvotes: 1

artm
artm

Reputation: 8584

You're getting img instead of a because even though your selector is a, img is what creates the event (event's source) and it bubbles up to the a, which you bind to. So event.target will be the img, not a. If you didn't have an img inside your a, the event.target would be the a. Also in your handler this refers to the widget because that's the final destination of the event before it reaches your handler. I don't think you have an option but to use closest().

See jquery cookbook, scroll up to 8.8

Upvotes: 1

Related Questions