Just in Chronicles

Life as a Voyage

Capturing TAB Keystroke with Javascript in Web Browsers

References:

Users on the Web don’t only use mouse for navigation, but also use their keyboard for fast and quick browsing. As a simple example, once they visit Google and type a keyword in the textbox, then they press the Enter key, rather than clicking the “Search” button. As another example, they use the TAB key to navigate menus.

These user actions sometimes cause unexpected results. Before the web 2.0 era, developers simply ignored these actions or prevented them from keyboard typing navigation. However, nowadays all user actions are allowed as far as they don’t break the web site, in terms of “user experience” or “usability”, or sometimes “accessibility”.

Therefore, developers need to identify what users do in a particular situation and prepare its reaction. Identifying the TAB keystroke is one of them.

Assuming that there are fields to be filled and validated before a certain transaction. When users enter nothing and press the TAB key, developers expect an error message appears and stay focused on the field. However, in our reality, regardless of the validation result, the focus moves onto the next field. That’s not what developers expect. In order for users to stay focused on the field, therefore, the following javascript code might be useful.

function checkTabKey(obj, e)
{
	var charCode = null;
	if ("which" in e) // NN4 & FF & Opera
		charCode = e.which;
	else if ("keyCode" in e) // Safari & IE4+
		charCode = e.keyCode;
	else if ("keyCode" in window.event) // IE4+
		charCode = window.event.keyCode;
	else if ("which" in window.event) // Other browsers support events
		charCode = window.event.which;
	else
		alert("the browser doesn't support");
	if (charCode == 9)
		setTimeout("document.getElementById(\"" + obj.id + "\").focus()", 1);
}

First of all, the code identifies what key has been typed. The keystroke event is stored in a different place, depending on browser types, so we need to detect it. Then, leave the focus to move onto the next field. After that, by using the setTimeOut() method, the focus is set back to the first field that the TAB key is typed.

That’s it for the TAB key detection. Let’s play with this!


자바스크립트로 탭키 잡아내는 방법. 탭키를 잡아내도 다음 필드로 이동하는 것을 막을 수가 없었지만, setTimeOut() 메서드를 이용하면 시간차로 잡아낼 수 있다.

Advertisements

Written by Justin Yoo

08/09/2009 at 01:13