Explain focus events in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

The focus event is fired when an element either gets or loses focus. Following are the focus events −

BlurThis event is fired when an element loses focus.
FocusThis event is fired when the element gets the focus.
focusinThis event is fired when the element is about to get focus.
ocusoutThis event is fired when an element is about to lose focus.

Following is the code for focus events in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   input {
      padding: 10px;
<h1>Focus events in Javascript</h1>
<form id="form">
<input type="text" placeholder="Username" />
<input class="passW" type="password" placeholder="Password" />
<h3>Focus on the above password input box to change its background color</h3>
   let passEle = document.querySelector(".passW");
   passEle.addEventListener("focus", () => {
      passEle.style.backgroundColor = "#90EE90";


On focusing on the password field −

Updated on 16-Jul-2020 13:21:46