×

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event.

What is focus() method?

When we want to focus on an element (if it can be focused) or basically highlight it, the focus() method is used.

This method is supported by mostly all the browsers like Google chrome, safari, Microsoft Edge/Internet Explorer, Oracle, Firefox etc.

NOTE: This method takes no parameters and has no return value as well.

Syntax:

element.focus()

Example:

<!DOCTYPE html>
<html>
<body>


Enter text here: <input type="text" id="tcontent">


<p>This is the example to show a how user can use focus method to an input element.</p>


<button type="button" onclick="myFunctiondemo()">Focus</button>


<script>
function myFunctiondemo() {
  document.getElementById("tcontent").focus();
}
</script>
</body>
</html>

Output:

Intially,

JavaScript Focus On Input

After the button has been selected, the text box gets highlighted

JavaScript Focus On Input

What is onfocus() event?

Whenever an element gets focus, the onfocus() event occurs.
The <input>, <select> and <a> use the onfocus() event commonly.
The onfocus() event can be used with all HTML tags expect for: <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> tags.
Similar to focus() method, the onfocus event is also supported by mostly all the browsers like Google chrome, safari, Microsoft Edge/Internet Explorer, Oracle, Firefox etc.

The input element and onfocus event

An input field is defined by the input tag where the user can enter data. The input tag element can be used to display several types of properties like radio buttons, text fields, checkboxes, dates, email Ids, passwords etc.

So, the onfocus() event or the focus method helps to set focus on the specified input element. The focused element helps in determining that which element will receive keyboard inputs and similar events by default.

The onfocus event can be used commonly in three ways:

  • In HTML,

Syntax:

<element onfocus= functionname>


<script>
function functionname(){
	//definition of the function
}
</script>

Example:

<!DOCTYPE html>
<html>
<body>


<p>This is the example to show a user can use "onfocus" event to an input element.</p>


Enter text here: <input type="text" id="tcontent" onfocus="myFunctiondemo()">


<script>
function myFunctiondemo() {
  document.getElementById("tcontent").style.backgroundColor = "lightblue";
}
</script>


</body>
</html>

Output:

Initially, the input element looks like this,

JavaScript Focus On Input

On focusing (selecting the input text-box):

JavaScript Focus On Input
  • In Javascript

Syntax:

<script>
object.onfocus = function(){functionname};


function functionname(){
	//definition of the function
}
</script>

Example:

<!DOCTYPE html>
<html>
<body>


<p>This is the example to show a user can use "onfocus" event to an input element.</p>


Enter text here: <input type="text" id="tcontent">


<script>
document.getElementById("tcontent").onfocus = function() {myFunctiondemo()};


function myFunctiondemo() {
  document.getElementById("tcontent").style.backgroundColor = "pink";
}
</script>


</body>
</html>

Output:

After the input element is focused (the text box is selected),

JavaScript Focus On Input
  • Using addEventListener() method in JavaScript

Syntax:

<script>
object.addEventListener("focus", functionname);
function functionname(){
	//definition of the function
}
</script>

Example:

<!DOCTYPE html>
<html>
<body>


<p>This is the example to show a user can use "onfocus" event to an input element.</p>


Enter text here: <input type="text" id="tcontent">


<script>
document.getElementById("tcontent").addEventListener("focus", myFunctiondemo);


function myFunctiondemo() {
  document.getElementById("tcontent").style.backgroundColor = "yellow";
}
</script>


</body>
</html>

Output:

After the input element is focused (the text box is selected),

JavaScript Focus On Input

NOTE: Internet Explorers and older versions do not support the method of addEventListener().

How to remove focus from the element?

  • By using the blur() method

Syntax:

element.blur()

Example:

<!DOCTYPE html>
<html>
<body>


Enter text here: <input type="text" id="tcontent">


<p>This is the example to show how a user can use blur method to an input element.</p>




<button type="button" onclick="myFunctiondemo()">Lose focus</button>


<script>


function myFunctiondemo() {
  document.getElementById("tcontent").blur();
}
</script>


</body>
</html>

Output:

When the text box is highlighted initially,

JavaScript Focus On Input

After the button has been selected, the text box loses focus

JavaScript Focus On Input
  • By using the onblur() event

Syntax:

<element onblur= “functionname()”>

Example:

<!DOCTYPE html>
<html>
<body>


<p>This is the example to show a user can use "onblur" event to an input element.</p>


Enter text here: <input type="text" id="tcontent" onblur="myFunctiondemo()">


<script>
function myFunctiondemo() {
  alert("Input field has lost focus.");
}
</script>


</body>
</html>

Output:

After the data has been entered in the input element, if the user clicks anywhere outside the field, it loses focus and an alert appears,

JavaScript Focus On Input

Related Topics

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.