How to simulate a click so that the current input loses focus using JavaScript

I have an input that in some cases has focus. If the user clicks the background of the page, the input loses focus. I tried to simulate a click on the background with the following code, but this does not work (you will notice that the input still has focus). Any suggestion on how to write code that mimics a click on the "background" of a page?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" ></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" ></script> <script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("main").focus(); }); </script> </head> <body> <div id="main"> <form action="/"> <p> <input type="text" id="input"/> </p> </form> </div> </body> </html> 
+7
javascript yui focus
source share
2 answers

I would suggest that using blur() would do the trick:

 <script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("input").blur(); }); </script> 
+18
source share

Try using the blur event. If you use jQuery, you can call the DOM object to create this event. The blur() method should also work without jQuery.

http://docs.jquery.com/Events/blur

+2
source share

All Articles