Skip to content

Instantly share code, notes, and snippets.

@evilmarty
Created November 4, 2011 01:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evilmarty/1338499 to your computer and use it in GitHub Desktop.
Save evilmarty/1338499 to your computer and use it in GitHub Desktop.
Mobile Safari form label to input focusing
// For use in jQuery
// Some mobile browsers (ie. Mobile Safari) don't focus their associated inputs
// so we force that behavior when possible.
$('label[for]')
// First we check when a label is touched and is associated with a radio or checkbox input,
// if so then we mark it as having focus.
.live('touchstart', function(event) {
var input = event.target.control ? $(event.target.control) : $('#' + event.target.htmlFor);
if (input.is('[type=checkbox], [type=radio]'))
input.focus();
})
// Should the user move via touch on the label instead of pressing on the label we blur the
// focus on the input if it's a radio or checkbox. This is to avoid misinterpreting a scroll
// for a press.
.live('touchmove', function(event) {
var input = event.target.control ? $(event.target.control) : $('#' + event.target.htmlFor);
if (input.is('[type=checkbox], [type=radio]'))
input.blur();
})
// If the press is finished and we still have focus on the radio or checkbox inputs then
// trigger a click event which will do the rest. Focus all other input types.
.live('touchend', function(event) {
var input = event.target.control ? $(event.target.control) : $('#' + event.target.htmlFor);
if (input.is('[type=checkbox], [type=radio]'))
if (input.is(':focus')) input.click();
else
input.focus();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment