How to simulate a click to make the current input lose its focus with JavaScript

24,362

Solution 1

I would imagine using blur() would do the trick:

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

Solution 2

Try using the blur event. If you're using jQuery there is a method you can call on the DOM object to raise this event. The blur() method should also work without jQuery.

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

Share:
24,362
avernet
Author by

avernet

Co-founder of Orbeon, developing Orbeon Forms: web forms, open source, for the enterprise. Passionate about technology, and how it improves the world.

Updated on November 20, 2020

Comments

  • avernet
    avernet over 3 years

    I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to write code that simulates a click on the "background" of the 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>
    
  • Dan Herbert
    Dan Herbert over 15 years
    oops, I didn't notice his script references. The blur() method will work regardless of framework though.
  • avernet
    avernet over 15 years
    Great stuff, thanks Paolo. I should have thought about it :).