revision:
The HTMLElement.blur() method removes keyboard focus from the current element.
The blur() method removes focus from an element.
HTMLElementObject.blur()
Parameters : none
const input = document.getElementById('first_name');
// Remove focus from specific element
input.blur();
// Remove focus from the currently active element
document.activeElement.blur();
<input type="text" id="sampleText" value="Sample Text" /> <br /><br />
<button type="button" onclick="focusInput()">Click me to gain focus</button>
<script>
function focusInput() {
const textField = document.getElementById("sampleText");
textField.focus();
// The input will lose focus after 3 seconds
setTimeout(() => {
textField.blur();
}, 3000);
}
</script>
<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>
example: click the buttons to give or remove focus from the text field
<div>
<input type="text" id="myText" value="A text field">
<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>
</div>
<script>
function getFocus() {
document.getElementById("myText").focus();
}
function loseFocus() {
document.getElementById("myText").blur();
}
</script>
example: ckick the buttons to give or remove focus from the link
Click the buttons to give or remove focus from the link above.
<div>
<a id="myAnchor" href="https://www.lwitters.com">Visit my website at lwitters.com</a>
<p>Click the buttons to give or remove focus from the link above.</p>
<input type="button" onclick="getfocus2()" value="Get focus">
<input type="button" onclick="losefocus2()" value="Lose focus">
</div>
<style>
a:focus, a:active {color: red;}
</style>
<script>
function getfocus2() {
document.getElementById("myAnchor").focus();
}
function losefocus2() {
document.getElementById("myAnchor").blur();
}
</script>
example: remove focus from a text input; the input will lose focus after 3 seconds
<div>
<input type="text" id="sampleText" value="Sample Text" /> <br /><br />
<button type="button" onclick="focusInput()">Click me to gain focus</button>
</div>
<script>
function focusInput() {
const textField = document.getElementById("sampleText");
textField.focus();
// The input will lose focus after 3 seconds
setTimeout(() => {
textField.blur();
}, 3000);
}
</script>