HTML DOM blur() Method


The HTML DOM blur() method is used to remove the keyboard focus from a specific element. Using blur we can add blur or remove blur to any HTML element. The blur() method can help in better navigation around the webpage as we can specifically focus on an element based on the user input.

Syntax

Following is the syntax for blur() method −

Object.blur()

Example

Let us see an example of the blur() method −

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   a{
      text-decoration:none;
      font-size:20px;
   }
   a:focus, a:active {
      color: red;
      text-decoration:underline;
      font-size:40px;
   }
</style>
</head>
<body>
<a id="Anchor" href="https://example.com">example.com</a>
<p>Give focus or remove focus…</p>
<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">
<script>
   function getfocus() {
      document.getElementById("Anchor").focus();
   }
   function losefocus() {
      document.getElementById("Anchor").blur();
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking “Get focus” −

On clicking “Lose focus”, it will be the same as original −

In the above example −

We have first created an anchor tag with id “Anchor” and href=”https://www.example.com” −

<a id="Anchor" href="https://example.com">example.com</a>

We have then defined two styles for the anchor tag to distinguish it when it is focused and active and when it is not.

a{
   text-decoration:none;
   font-size:20px;
}
a:focus, a:active {
   color: red;
   text-decoration:underline;
   font-size:40px;
}

We have then created two buttons “Get focus” and “Lose focus” to execute getfocus() and losefocus() functions respectively.

<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">

The getfocus() function gets the element which has “Anchor” id associated with it which in our case is <anchor> element.It then executes it focus method which will change the links to the a:focus,a:active style i.e the color will be green, text will be underlined and font size increased to 40px.

function getfocus() {
   document.getElementById("Anchor").focus();
}

The losefocus() function gets the element which has “Anchor” id associated with it which is the <anchor> element in our case. It then executes its blur() method to loose focus from the above link and changes the link style to the original style for <a> element.

function losefocus() {
   document.getElementById("Anchor").blur();
}

Updated on: 20-Feb-2021

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements