Javascript auto accesskey wireup for accessibility

Categories Uncategorized

 

Although accessKey is controversial as an accessibility feature, this small experiment demonstrates how one can automatically add functionality to a web page, by means of separation of concerns, with minimal code changes.

This example uses prototype.js, a small, very useful library that provides cross-browser functionality.

Separation of concerns, in the case of web applications and web pages dictates that, for the purpose of maintaining clean structured markup, one should separate presentation(in the form of CSS), business logic (in the form of js) and structured markup.

For the purpose of this exercise, the following Javascript code snippet, combined with prototype.js automatically adds accesskey attributes to the first 20 links contained in div elements with the id’s navigation, navbar or menu.

Because we don’t want to call the javascript function from within structured markup, i’ll use a variant of Scott Andrew LePera’s addEvent:

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

The addEvent function will add a hook to the onload event of the page, calling our function. Next, using prototype, we can define a function that automatically adds accesskey attributes to all a child nodes of out div’s. We can do it like this:

function enableAccessKeys(){
 var menu = $$('#navigation a','#navbar a', '#menu a');
 var validKeys = ['q','w','r','t','y','u','i', 'g', 'j', 'k', 'l']
 for(i=0;i<menu.size();i++) {="" var="" theelementtext="menu[i].innerHTML;" if(i<10)="" menu[i].accesskey="i+1;" else="" if(i="">9 && i<21)
        {
            menu[i].accessKey=validKeys[i-10];
        }            
    }
}

In the above script, by using the validKeys array, I am defining 11 more possible accesskeys (just some more), because normally we would only use numbers, as per WAI advice. The letters contained in the validKeys array are letters that are uncommon for browser hotkeys (ALT+ hotkeys anyway).

For the final touch, we hook up the function to the onload event like this:

    
        addEvent(window, 'load', enableAccessKeys);

Update: I consider the addEvent function obsolete, as prototype.js’s Event.observe function is everything you need as far as event listeners go.
You can read more about it here.

This exact code is enabled on this page, automatically adding accesskey attributes to the above menu items. The javascript code can be downloaded here.

To test this, you can press ALT+SHIFT+1 for Firefox or ALT+1 followed by Enter for Internet Explorer. It will take you to the first link (Home).

 

Leave a Reply

Your email address will not be published. Required fields are marked *