Last active
August 29, 2015 14:02
-
-
Save patrickfox/e98810d83585ed53066f to your computer and use it in GitHub Desktop.
Accessibility Tools: Focus on anything with access()
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
/* | |
$(selector).access(focus_only) | |
@param(bool): focus_only - true, false(default) | |
Problem: | |
Manually managing focus is cumbersome and pollutes the DOM with @tabindex. | |
Solution: | |
access() provides a common and consistent means of focusing on any element. | |
Importance of Focus Management: | |
Placing focus allows us to: | |
-orchestrate the users flow | |
-ensure that focus order is preserved and that logical | |
-speak the contents of a container - this doesn't work consistenly under all situations and varies from one browser/AT combo to another | |
Usage: | |
Place focus in an area: | |
$('#my_element').access(true); --> creates a temp span before the target element, focuses on it, and removes it when it loses focus | |
Place focus on an element: | |
$('#my_element').access(); --> stores existing tabindex value, adds tabindex=-1, places focus on element, and on blur removes focus handler and restores original tabindex value | |
*/ | |
$.fn.access = function(focus_only) { | |
var target, temp_em; | |
if (focus_only) { | |
temp_em = $('<span />'); | |
temp_em.insertBefore(this); | |
temp_em.attr('tabindex', '-1').on('blur focusout', function() { | |
return $(this).remove(); | |
}).focus(); | |
} else { | |
target = $(this); | |
target.data('original-tabindex', target.attr('tabindex') || false); | |
target.attr('tabindex', '-1').on('blur focusout', function() { | |
if (target.data('original-tabindex') !== false) { | |
target.attr('tabindex', target.data('original-tabindex')); | |
} else { | |
target.removeAttr('tabindex'); | |
} | |
if (target.is('select')) { | |
target.parent().removeClass('ui-focus'); | |
} | |
target.off('blur focusout'); | |
return target.data('original-tabindex', false); | |
}).focus(); | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment