0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

brilliant. Thank you very much. Here is the demo with your fix: jsfiddle.net/ech2htrt/3
1

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

1 Comment

Thank you very much for your reply. I will look into the event bubbeling and try to adapt to this concept. I will leave this question open for little while to see if other persons may have a different approach.

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.