WebAIM - Web Accessibility In Mind

E-mail List Archives

Thread: onClick and onKeypress

for

Number of posts in this thread: 2 (In chronological order)

From: R Sengers
Date: Tue, Oct 04 2005 8:40AM
Subject: onClick and onKeypress
No previous message | Next message →

We're working on a site that needs to be Section 508-compliant. We have a link that has a onclick event on it. (We also provide an alternative for users who do not have JavaScript enabled.) Someone told us we need to add a second, redundant onkeypress event to the onclick event (both would do the same thing), to make it more accessible. Is this correct?

W3C's WCAG guidelines says you should use onClick with onKeypress. The US government's guidelines and tips (at access-board.gov) do not mention the onKeypress event. For onClick, they say "it works well with screen readers."

I understand there are some possible issues with onKeypress:

It means that pressing any alphanumeric key will invoke the event, not just the Enter key. Which might be unexpected behavior, for someone who expects only the Enter key have an effect on the link.

Also, having an onClick and an onKeypress event may sometimes cause the event to be fired twice.

Can you tell me any other pros and cons for adding a redundant onKeypress event?

Thanks
Rachel Sengers




From: Alex Bovey
Date: Tue, Oct 04 2005 9:20AM
Subject: Re: onClick and onKeypress
← Previous message | No next message

Adding an onkeypress event handler won't help at all if they don't
have Javascript enabled, since the onkeypress will still call a
Javascript function. However, onclick assumes that your users are
using a mouse, which they may not be, and that's the reason for using
onkeypress as well. So what you would do is this:

<a href="#" onclick="myJavascriptFunction()" onkeypress="this.onclick()">

This means that if they're using a keyboard they will still be able to
call the function, and whatever happens the event won't be called
twice.

In order to cater for the people that don't have javascript enabled
you should put a link to a page in the href attribute that will act as
an alternative:

<a href="my_alternative.html" onclick="myJavascriptFunction(); return
false;" onkeypress="this.onclick()">

Notice the "return false" that's been added after the call to the
Javascript function. This is to prevent the href being followed AND
the Javascript function being called, which you probably don't want.

HTH,

Alex

--
Alex Bovey