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?
onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however. In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE.
The onfocusout event occurs when an element is about to lose focus. Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you should use the onfocusout event.
The onblur attribute fires the moment that the element loses focus. Onblur is most often used with form validation code (e.g. when the user leaves a form field). Tip: The onblur attribute is the opposite of the onfocus attribute.
The focusout event fires when an element has lost focus, after the blur event. The two events differ in that focusout bubbles, while blur does not. The opposite of focusout is the focusin event, which fires when the element has received focus.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With