HTML DOM focus() method

HTMLWeb DevelopmentFront End Technology

The HTML DOM focus() method is used for giving focus to an HTML element . Focus cannot be applied to all the HTML element.For eg: You cannot focus a <p> tag. To remove the focus from an element use the blur() method.

Syntax

Following is the syntax −

HTMLElementObject.focus()

Example

Let us look at an example of the focus() method −

<!DOCTYPE html>
<html>
<head>
<style>
   input[type=text]:focus, p:active {
      color: blue;
      font-size:35px;
      background-color:lightpink;
      border:2px solid blue;
   }
   input[type=text]{
      color:black;
      font-size:20px;
   }
</style>
<script>
   function enableFocus() {
      document.getElementById("USR1").focus();
   }
   function disableFocus() {
      document.getElementById("USR1").blur();
   }
</script>
</head>
<body>
<h1>focus() method example</h1>
<label>USERNAME :<input id="USR1" type="text" size=5 maxlength=10></label>
<br><br>
<input type="button" onclick="enableFocus()" value="FOCUS">
<input type="button" onclick="disableFocus()" value="BLUR">
</body>
</html>

Output

This will produce the following output −

On clicking the FOCUS button −

On clicking the BLUR button −

In the above example −

We have first created a text box with id “USR1” and size and maxlength property value equal to 5 and 10 respectively.

<label>USERNAME :<input id="USR1" type="text" size=5 maxlength=10></label>

We have created two different css styles when the textbox has been in focus, active and when it is not −

input[type=text]:focus, input[type=text]:active {
   color: blue;
   font-size:35px;
   background-color:lightpink;
   border:2px solid blue;
}
input[type=text]{
   color:black;
   font-size:20px;
}

We have then created two buttons FOCUS and BLUR that will execute the enableFocus() and disableFocus() method respectively when clicked by the user −

<input type="button" onclick="enableFocus()" value="FOCUS">
<input type="button" onclick="disableFocus()" value="BLUR">

The enableFocus() method gets the input element with type “text” using the getElementById() method and enables its focus() method to set focus on the textbox which applies our :focus style to our textbox. The disableFocus() method gets the input element with id “USR1” and calls the blur() method on it which removes the focus from the textbox which applies our normal css style to it i.e it gets back to default style −

function enableFocus() {
   document.getElementById("USR1").focus();
}
function disableFocus() {
   document.getElementById("USR1").blur();
}
raja
Published on 19-Aug-2019 11:22:05
Advertisements