Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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')).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top