jQuery: Switching The Focus Between Two Form Fields

jQuery: Switching The Focus Between Two Form Fields

In the last version of my Google Translator widget for Opera I had to solve one problem – how to switch the focus between two textareas by clicking on a hotkey.

In this article I want to share jQuery script, that solves this problem. May be it will be usefull for someone.

What is interesting, while I wrote this post and have tested the script, I reduced its size about 2.5 times compared with the original version (this suggests that the same problem can be solved in different ways and always need to try to optimize JavaScript scripts).

Now lets look at the script:

$(function() {

	/* Adding a class to TEXTAREA to determine the focus */
	$('textarea').focus(function() {

	/* Putting the focus by default on a first TEXTAREA */

	/* Switching the focus by clicking Enter */
	$(document).keypress(function(e) {
		if(e.which == 13) {
			return false;


What we doing in this script? We add the .hasFocus class to the focused textarea, remove this class from a field that is not focused, and while pressing Enter focus switches to a textarea, that has no this class.

May be there is a shorter way to do the same, but, unfortunately, I not found simpler way to get a field, that has not the focus.


Look at the script in action.

Lеаvе а Соmmеnt

© 2009–2022 Dimox.net  •  Privacy Policy