Clicking out of a dropdown with Scriptaculous/Prototype

Posted on July 22, 2010

I’m posting this in the hopes that it saves someone a few hours. I recently had to implement a multi-select dropdown using Prototype and Scriptaculous. The big hurdle I encountered was trying to hide the dropdown part when the user clicks out. Here’s what the HTML looks like:

<div>
 <div onclick="Effect.toggle('dropdown')">Click to select...</div>
 <div id="dropdown" style="display:none">
  (select a filter)
 </div>
</div>

So what I want is that, when the person clicks out of the dropdown, it hides. For reference, we have a container div that contains the whole screen. Here’s the Javascript.

$("container").observe('click', function(e) {
 var dropdown = $("dropdown");

 var row = Event.element(e);

 if(row !== dropdown && !row.descendantOf(dropdown))
  dropdown.hide();
});

And that’s really all there is to it. After using jQuery for quite some time, having to switch back to writing out stuff like this is a little jarring, but what can you do.

Leave a Reply

Your email address will not be published. Required fields are marked *