jQuery Toggler
I often like to have small form actions in my sidebar hidden away with javascript that are just a toggle away. Using jQuery to do this is quite easy but there are a few gotchas. Firstly we want both the always visible toggler link and a cancel button inside the toggled div to do the toggling. Next we want the first form input in the toggled div to become focused when we make it visible. It is important we don’t try and do this when we are toggling the div off (hiding it) as Internet Explorer will bork when you try and focus on a hidden element.
Starting with our HTML:
<div class="toggle">
<h2><a href="#new_category" class="toggler">Create New Category</a></h2>
<div class="togglable">
<form action="/" method="post">
<p>
<label for="category_name">Name: </label>
<input id="category_name" name="category[name]" size="20" type="text" />
</p>
<p>
<input id="category_submit" name="commit" type="submit" value="Create Category" />
or
<a href="#" class="toggler">Cancel</a>
</p>
</form>
</div>
</div>
Now the JS:
////
// Behaviours
$(document).ready(function() {
////
// Automatically hide all togglable elements on load
$('.togglable').hide();
////
// Toggle a .togglable div inside the clicked parent .toggle div
$('a.toggler').click(function() {
var togglable = $(this).parents('.toggle').children('.togglable')
togglable.toggle();
if(togglable.is(':visible')) {
togglable.find('input:visible:enabled:first').focus();
};
return false;
});
});
The sense in this is that I traverse up to the parent div ’.toggle’ before filtering down to ’.togglable’, this way I can click both the ‘h2 a’ and the ’.togglable a’ to get the same effect. Also then I make sure that I don’t try and focus on a hidden element because just doing ‘input:visible:enabled:first’ won’t check if any of it’s parents are hidden.
See the Demo Page.
BTW Google Hosted JS FTW!