JavaScript Focus method

JavaScript focus method can be used to set focus to the current window, to the input text box , to the specific button or to any radio button and many more elements.

JavaScript Focus method

JavaScript focus() method is used to set focus to an element. The element can be text box, button, current window or any element. Generally when we do coding then we want to set the focus to a particular element or any text box ,combo box or in the window then focus method is used.

Syntax :


The focus method will support in all browser.

JavaScript focus is used to set the focus or get the focus. It can be apply to text box, text area, combo box or any element in the form. Using this example we will help you to understand the focus method in JavaScript.

Example :At first we have created a html page in which there are two text boxes and two buttons. Now, when user click on first button then focus is set to first text box and when the user click on second button then the focus will set to second text box.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="" xml:lang="en" lang="en"> 
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 
<title>JavaScript focus() method example</title> 
<body bgcolor="#C0C0C0" >JavaScript focus() method example
<script type="text/javascript"> 
function setFocus(a){ 
if(a == 1){ 
}else if(a == 2){ 
<form name="Form" action="#"> 
<input type="textbox" name="Textbox1" value="First text box"></input>The first text box 
<br /> 
<input type="textbox" name="Textbox2" value="First text box"></input>The second text box 

<input type="button" value="Click to Focus on first textbox" name="Button1" 
onclick="setFocus(1)" /> 
<input type="button" value="Click to Focus on second textbox" name="Button2" 
onclick="setFocus(2)" /> 

Output from the program is as follows:

When you click on button "Click to Focus on first textbox"  then focus will beset to the first text box as you can see in the below output:

And, when you click the button "Click to Focus on second textbox" the focus will set to the  second text box as you can see the below output:

Download Source Code

Share on Google+Share on Google+

JavaScript Focus method

Posted on: July 4, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: JavaScript Focus method  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image