views:

23

answers:

1

I am trying to figure out how to use the dom to access the access keys of each access keyed link and underline the first character of all of the links on the page when the access key is pressed.

i.e. when the person presses alt in IE and Chrome all of the first letters of the links underline letting the person know which key to press. Also is there anyway to do it by creating a universal [access key] for all browsers using javascript or are you forced to use the multiple methods for each browser and thus stuck writing a class for each browser?

I found one way using a <span> around the character, but that just doesn't seem like good practice and it would be nice if the dom would just grab the access key and underline the letter in the link and modify it with an underline.

Any help is greatly appreciated.

+1  A: 
var labels= document.getElementsByTagName('label');
for (var i= labels.length; i-->0;) {
    var label= labels[i];
    if (!label.htmlFor) continue;
    var field= document.getElementById(label.htmlFor);
    if (!field) continue;
    if (!field.accessKey) continue;
    var ix= label.firstChild.data.toLowerCase().indexOf(field.accessKey.toLowerCase());
    if (ix===-1) continue;
    var next= label.firstChild.splitText(ix+1);
    var span= document.createElement('span');
    span.className= 'accesshighlight';
    span.appendChild(label.firstChild.splitText(ix));
    label.insertBefore(span, next);
}

This will wrap a <span class="accesshighlight"> around the first matching letter in a label, assuming that labels contain text content and not more elements (if you need to look for matching text in subelements that's a bit more time-consuming). Then you can say:

body.showhighlights .accesshighlight {
    text-decoration: underline;
}

and toggle the presence of class="showhighlights" on document.body when alt is pressed.

bobince