Created
November 4, 2011 01:59
-
-
Save evilmarty/1338499 to your computer and use it in GitHub Desktop.
Mobile Safari form label to input focusing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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