Created
October 5, 2014 22:11
-
-
Save ethanresnick/6bae51f1cde910a9cc06 to your computer and use it in GitHub Desktop.
Form Help Text
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
//forms help text | |
jQuery(document).ready(function($) { | |
var forms = $('form'), className = 'visually-hidden'; | |
//hide all help-text and make links in help text untabbable (because the text itself is hidden) | |
$('.help-text:not(.help-text-group)', forms).addClass(className).find('a').attr('tabindex', '-1'); | |
//listen to any changes of focus within our forms (uses event delegation for speed) | |
forms.delegate("input, select, texarea, .tinymce", "focusin focusout", function(event) { | |
var $this = $(this), labelId, helpText; | |
//find the help text associated with the element whose focus changed (using some magic if it's | |
//the tinymce element that changed, as tinymce doesn't throw focus events automatically because | |
//it's really an iframe, but's been hacked to trigger a focus change on the parent div) | |
labelId = $this.is('.tinymce') ? $this.find('textarea').eq(0).attr('id') : $(this).attr('id'); | |
helpText = $('label[for="' + labelId + '"] .help-text', event.delegateTarget); | |
//toggle the help-texts visibility and, if its visible, make links within it focusable again. | |
helpText.toggleClass('visually-hidden'); | |
helpText.find('a').attr('tabindex') ? helpText.find('a').removeAttr('tabindex') : helpText.find('a').attr('tabindex', '-1'); | |
}); | |
//if we focus on the help-text (meaning it has an <a> making it focusable), it would disappear | |
//because the input showing it would loose focus. This prevents that by showing it when it gains | |
//focus (and then hiding it again when we move off, letting the thing we move into (maybe its input, maybe not) | |
//decide if it should be made visible again. | |
forms.delegate(".help-text:not(.help-text-group)", "focusin focusout", function() { | |
$(this).toggleClass(className); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment