If you need an element, like a <h3>, to have an 'onclick' event handler, then you should also provide an 'onkeypress' event for keyboard users.
In the case of using a standard <a> tag, this is not required, as most browsers also trigger the 'onclick' event for keyboard users.
Unfortunately, for other tags, its not as simple as adding an 'onkeypress' event, as this will also trigger when the user presses the [tab] key.
The following function provides a generic solution to this:
function addLinkEvent(link, func) {
try {
link.style.cursor = 'pointer';
} catch (e) {
try {
link.style.cursor = 'hand';
} catch (e) {
}
}
link.onclick = func;
link.tabIndex = 0;
link.onkeypress = function (e) {
var keyCode = e ? e.which : window.event.keyCode;
if (keyCode != 13 && keyCode != 32) return true;
this.onclick();
return false;
};
}
And for an example of its usage:
function functionName() {
alert('hi');
}
var heading = document.getElementById('myHeading');
if (heading) {
addLinkEvent(heading, functionName);
}
This function has been tested in:
Unfortunately both Safari 2 and Firefox 1 do not allow the user to [tab] to the (fake) links. In these cases though, the cursor effect and 'onclick' work as normal, but the keyboard access is ignored.
I should point out that this function should not be used to create the effect of an actual link... use the right tool for the job. Take a look at how you can do pop-up windows in JavaScript for an example.
Also remember that not all users, like search engine spiders, have JavaScript enabled, so this function should really only really be used in unobtrusive JavaScript.
Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.