[javascript] blur() vs. onblur()

I have a input tag with an onblur event listener:

<input id="myField" type="input" onblur="doSomething(this)" />

Via JavaScript, I want to trigger the blur event on this input so that it, in turn, calls the doSomething function.

My initial thought is to call blur:

document.getElementById('myField').blur()

But that doesn't work (though no error).

This does:

document.getElementById('myField').onblur()

Why is that? .click() will call the click event attached to an element via the onclick listener. Why does blur() not work the same way?

This question is related to javascript jquery onblur

The answer is


Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.


I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button