Clickable <label>s in Safari

Today while testing the latest release of our CMS system, I noticed that Safari doesn’t actually do anything interesting with its <label> tags. Firefox and other right-thinking browsers allow one to click on a label and to activate the corresponding form element.

Fortunately, with a little Javascript-Fu, we can add this behavior for Safari as well. Here’s the script we wrote to bring Safari up to snuff:

// Make label elements clickable in Safari
Event.observe( window, "load", function() {
	if ( Prototype.Browser.WebKit ) {
		$$('label').each( function( item ) {
			Event.observe(item, "click", function(){
					var target = $(this.getAttribute('for'));
					// Checkboxes or radio button labels
					if( target.type == 'checkbox' || target.type == 'radio' )
						target.checked = target.checked == false ? true : false;
					else // Textareas and input fields, Select elements
						target.focus();
				});
		});
	}
});

This does require Prototype to work, of course, so if you haven’t developed the abiding love for it that we have, you’ll need to rewrite some bits to get them to work without it. There’s also something similar out there for jQuery if you swing that way.

(Our version is based on this one, but is simplified a bit by taking advantage of some of prototype’s newer utility functions.)

Leave a Reply