To remove the focus on an input
tag element in HTML, you can use the blur()
method on the element using JavaScript.
// remove focus from the element
element.blur();
Let's say we have an input
tag and a button
like this,
<!-- Input tag -->
<input id="myInput" type="text" placeholder="Enter some text here" />
<!-- Button -->
<button id="myBtn">Click to remove focus from input</button>
This input tag will be already focussed when a user visits the website and we want to remove the focus when we click the button
below it.
We can achieve this functionality using the blur()
method on the input
element.
// first get a reference
// to the input tag and button
const input = document.querySelector("#myInput");
const button = document.querySelector("#myBtn");
// use the focus method
// to focus input tag
// when user visits
input.focus();
// attach a click handler
// to button element
button.addEventListener("click", () => {
// when user clicks the button
// remove the focus form the input tag
// We can use the blur() method on the
// input element to acheive that
input.blur();
});
Now the input
tag focus will be removed when clicked on the button
element.
See this example live in JSBin.