How to Unfocus an Input Field With Javascript

Written by steve mcdonnell | 13/05/2017

In JavaScript, when you put focus on a field, for example on a text box in an HTML input form, it makes that field active and places the blinking cursor inside the field. A user can type information into the field without having to click in it first. The opposite of focus is blur, and to unfocus a field using JavaScript, you apply the blur method to the JavaScript object.

Create a new HTML document in an editor. For example, type "nano noedit.html" to create a new document using the Nano text editor in Linux. You can use Notepad or any other text editor of your choice. Name the file noedit.html.

Add the HTML headers. Create an input form with two text fields, where the first is not editable and the second is editable. When the first fields gains focus, unfocus the field using the blur method. For example, type:

Cannot Edit

Cannot edit this field:

Edit this field:

Exit the editor and save the file. Navigate to the HTML file in a browser to test the functionality.

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.