javascript - unfocus a textbox

Use the blur() method or try setting the focus on another element like a link.


This is what I used when .blur() didn't want to be my friend

function blurAll(){
 var tmp = document.createElement("input");
 document.body.appendChild(tmp);
 tmp.focus();
 document.body.removeChild(tmp);
}

You can make use of element.disabled parameter in javascript.

Example:

<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="myText">

<p>Click the button to unfocus the text field.</p>

<button onclick="myFunction()">Unfocus input</button>

<script>
document.getElementById("myText").focus();
function myFunction() {
	
  	document.getElementById("myText").disabled = true;    
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>

`


If you don't have easy access to the specific element that you want to blur, there is a slightly hacky way you can implement "blur all" functionality.

Just add the following HTML somewhere on your page:

<input id="blur-hack" type="text" style="position: absolute; opacity: 0;">

Then this JS will unfocus anything currently focused:

document.getElementById("blur-hack").focus();

Note that for the inline HTML styling, we can't do display: none or else you can't focus on it. position and opacity will adequately remove the element from the flow - you could also use margins to shove it way off the page, etc.

Tags:

Javascript