Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use javascript onclick on a DIV tag to toggle visibility of a section that contains clickable links?

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?

like image 728
Miro Solanka Avatar asked Jan 04 '09 17:01

Miro Solanka


1 Answers

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.

like image 152
Aron Rotteveel Avatar answered Oct 04 '22 18:10

Aron Rotteveel