[Javascript] Help with closures

Bill Moseley moseley at hank.org
Thu Jan 11 17:57:58 CST 2007


Or I think this is a closure issue.

I have a really simple and common task (that I'm likely making hard), where I
want to create a hide/show block.

So, the block of HTML looks basically like this:

    <div class="hidable">

        <div class="content">
            <span class="click">Hide this content</span><br />
            content here
        </div>

        <div class="hidden">
            <span class="click">Show the content</span>
        </div>

    </div>

So clicking on "Show" or "Hide", well shows or hides that block with
content.

The problem is when I have two of those blocks clicking on the "hide"
seems to get the right event but is hiding the wrong block.

Here's a working demo:

    http://hank.org/hide.html



So, a page can have any number of the above blocks.  The javascript
finds the blocks by looking for all "hidable" classes using Prototype's
getElementsByClassName();

The onclick events are assigned to the spans with "click".  When the
even first I look at the parentNode's class name to know if should
hide or to show.

Basically in pseudo code I set up the events like so:

    for div in get_by_class( 'hidable' ) {

        // get <div> elements for the two inner sections
        var content_div = get_class( 'content', div );
        var hidden_div  = get_class( 'hidden', div );

        // get the span for setting the events
        var show_span   = get_class( 'click', content_div );
        var hide_span   = get_class( 'click', hidden_div );

        // closure to call the toggle passing in the two <div>s
        var click_event = function(e) {
            toggle( e, content_div, hidden_div );
        }

        Event.observe( show_span, 'click', show_event, false );
        Event.observe( hide_span, 'click', show_event, false );
    }


Then the event does:

function toggle ( event, content_div, hidden_div ) {

    look at event element's parent's class name to determine if should
    hide or show.

}



-- 
Bill Moseley
moseley at hank.org




More information about the Javascript mailing list