focus() In JavaScript

focus() method focuses on the element of a window.

focus() In JavaScript

focus() In JavaScript

In this section we will read about how to specify the focusing location on a window.

focus() method in JavaScript is used to specify the element to be focused in current window. It specifies the current position of cursor that over which element the cursor is focusing. The element could be a textbox, radio button, checkbox, button, label etc. This method helps the programmer to make the user-friendly GUIs. Using this method a programmer can add the feature of dynamic focusing to the element on a current window that a user can easily understand using which element the information has to be provided. focus() method can be used to focus the current window also.

Syntax

Syntax to focus elements.

HTMLElementObject.focus()

Syntax to focus window.

window.focus()

Example

Here I am giving a simple example which will demonstrate you about how to get focus on the element. In this example I will create an HTML page where I will create a GUI form with some HTML elements. In this HTML page we will write the Javascript code for focusing on the element, removing the focus from the element, and getting the value what is entered inside the textbox.

focusExample.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Focus Elements Example</title>
<script>
function getfocus()
{
//var totalElem = document.form1.elements.length;
//alert('total num of elements : '+totalElem); 

var elem = document.getElementById('form1').elements; 
elem[0].focus(); 
}
function losefocus()
{
var elem = document.getElementById('form1').elements; 
elem[0].blur()
}
function displayValue()
{
document.getElementById('lblValues').innerHTML = "Your Name : " +
document.getElementById('name').value 
}
</script>
</head>
<body>
<form action="#" id="form1" onsubmit="displayValue()">
<p>Enter your name : <input type="text" id="name"/></p>
<p><input type="submit" value="Submit"/> &nbsp; &nbsp; 
<input type="button" value="Get Focus" onClick="getfocus()"/>&nbsp; &nbsp; 
<input type="button" value="Loose Focus" onClick="losefocus()"/>
</p>
</form>
<div id="lblValues"></div>
</body>
</html>

Output

When you will execute the above example you will get the output as follows :

In the above GUI when you will click on the "Get Focus" button then the cursor will be blinking in the textbox and if you click on the "Loose Focus" button then the cursor will be disappear from the text box and if you click on the submit button after giving some text then the text given by you will be displayed in bottom of the GUI as follows :

Download Source Code

Code for download is given as a text file, to run first download the source code and save it as HTML format and then open it with the compatible browser.