HTML - DOM blur() Method



The HTML DOMblur()method is used to remove keyboard focus dynamically from an element in the HTML DOM. Removing focus from an element refers to shifting the keyboard focus away from a specific element, such as an input field or a button.

The DOM provides another method namedfocus(), which you can use to give focus on any Element in HTML DOM.

Syntax

Following is the syntax of the HTML DOM blur() method −

Object.blur();

Parameters

This method does not accept any parameter.

Return Value

This method does not return any value.

Example 1: Remove Focus from the Input Field

The following is the basic example of the HTML DOM blur() method to remove focus from an input field when a button is clicked −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body>
<p>Click the button to blur the input field.</p>  
<input type="text" id="myInput" placeholder="Type something...">
<button onclick="blurInput()">Blur Input</button>
<script>
   function blurInput() {
      const input = document.getElementById('myInput');
      input.blur();
   }
</script>
</body>
</html>

Example 2: blur() method on anchor (<a>) element

Following is another example of the HTML DOM blur() method. We use this method to remove focus from an anchor (<a>) element −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body> 
<p>Click the button to blur the anchor element.</p>
<a id="myAnchor" href="https://www.example.com">Example Anchor</a>
<button onclick="blurAnchor()">Blur Anchor Element</button>
<script>
   function blurAnchor() {
      const myAnchor = document.getElementById('myAnchor');
      myAnchor.blur();
      alert('Anchor element blurred!');
   }
</script>
</body>
</html>  

Example 3: Blurred on Clicking Anywhere

The below example shows how the blur() method works with the event listener. When you click the input field and outside the field, a pop-up will display with the message "Input field is blurred" −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body>
    <p>Click anywhere outside the input field to blur it.</p>
    <input type="text" id="myInput" value="Edit Me!">

    <script>
        const myInput =document.getElementById('myInput');
        myInput.addEventListener('blur', () => {
            alert('Input field blurred!'); 
        });
    </script>
</body>
</html>     

Supported Browsers

Method Chrome Edge Firefox Safari Opera
blur() Yes Yes Yes Yes Yes
html_dom.htm
Advertisements