views:

11134

answers:

3

Hi I've got a DIV section that has only its title visible initially. What I would like to achieve is that when the visitor clicks anywhere on the area of toggle_section the toggle_stuff div toggles between visible/hidden.

<div id="toggle_section" 
     onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');">
    <div id="toggle_title">Some title</div>
    <div id="toggle_stuff">
        some content stuff
        <a href="/foo.php">Some link</a>
    </div>
</div>

However, the way it is set-up right now, if I have any <a> link within the toggle_section, clicking that link will also execute the onclick event.

Then my question is what would be the best way to set this type of behavior?

A: 

I don't really know if this would work, but try giving the link element a bigger z-index value than the toggle_section div.

something like :

#toggle_section a { z-index: 10; }
andyk
+4  A: 

The most simple solution is to add an extra onclick handler to the link within your DIV which stops event propagation:

<div id="toggle_section" 
     onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');">
    <div id="toggle_title">Some title</div>
    <div id="toggle_stuff">
        some content stuff
        <a href="/foo.php"
            onclick="Event.stop(event);"
        >Some link</a>
    </div>
</div>

The above example uses Prototype's Event.stop() function in order to facilitate a cross browser event propagation stop.

As you use the inline onclick() handler, most (if not all) browser will traverse the event in the bubbling phase first (which is what you want).

A good guide to understanding the actual reasons behind this behaviour and the differences between event capturing and event bubbling can be found at the excellent Quirksmode.

Aron Rotteveel
+1  A: 

After I posted my first question I could not wait to try to think about it once more and it seems that I have found a quite simple way to achieve this.

I have moved the onlick Effect.toggle into a separate function like:

function someClick(event) {
    if (event.target.nodeName == 'A') {
        return;
    } else {
        new Effect.toggle('toggle_stuff', 'slide');
    }
}

I suppose this would only work for A tags and not anything else that is clickable though.

Miroslav Solanka