blu
blu

Reputation: 13175

Why does this Prototype code work like this?

This is my html:

(note: I didn't use a background image on the a just for simplicity to show someone how this could work)

<div class="foo">
    <ul>
        <li><a href="#" class="bar"><img src="bar.gif" /></a></li>
        <li><a href="#" class="baz"><img src="baz.gif" /></a></li>
    </ul>
</div>

And my JavaScript:

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        $$('.foo a').each(function(a) {
            alert(a); // this is the anchor
            a.observe('click', fooClick);
    });

    function fooClick(event) {
        alert(event.element()); // this is the img
    }
</script>

Why is the element in fooClick the image and not the anchor? How should I have done this to use the image.

Upvotes: 0

Views: 139

Answers (3)

NilColor
NilColor

Reputation: 3542

If you will use images as a background you should get an anchor as event.element(). I think event.element() is a same as event.target and this is an element that received an event first and from which this event is bubble up the DOM. So remove (move it to css/background-image) or check for element() parent.

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125498

Whilst the click handler is bound to the anchor, the click event is raised on the image. The event bubbles up the DOM and the event handler on the anchor gets called. event.element() is the element that the event was raised on

Upvotes: 3

Matt Molnar
Matt Molnar

Reputation: 2542

Somewhat confused at your question, "Why is the element in fooClick the image and not the anchor? How should I have done this to use the image."

Did you mean "anchor" in the last sentence? If so, event.element() is the actual element that was clicked, not necessarily the element that has the handler assigned to it. If you need the anchor you can just do something like alert(event.element().up('A')).

Upvotes: 2

Related Questions