[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


This:

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

works because your element (the <input>) has an attribute called "onblur" whose value is a function. Thus, you can call it. You're not telling the browser to simulate the actual "blur" event, however; there's no event object created, for example.

Elements do not have a "blur" attribute (or "method" or whatever), so that's why the first thing doesn't work.


Similar questions with javascript tag:

Similar questions with jquery tag:

Similar questions with onblur tag: