trigger focus event will fires blur event(without use alert and browser console)

3.4k views Asked by At

jsfiddle link

<input id = "focus-ipt" type = "text" value = "nothing" />

var $focusIpt = document.querySelector( "#focus-ipt" );
$focusIpt.addEventListener( "blur", function ( e ) {
   $focusIpt.value = "blured!";
} );
setTimeout( function () {
    $focusIpt.focus();
    }, 1000 );

I just trigger focus event,but blur event fired after focus; I searched for a long time, close the console, use setTimeout,however, can't solve it;I really don't konw how this happened,can anyone help me?

1

There are 1 answers

6
Obsidian Age On BEST ANSWER

This is actually not the case; focus() does not automatically trigger blur().

The blur() is getting triggered because you are interacting with the DOM. By clicking on one of the buttons in your fiddle (such as Run or Tidy), the #focus-ipt element is no longer active -- the button you're clicking on is.

If you simply wait the time out, without doing anything, the blur() event won't occur. As soon as you click off of the input, the blur() will occur.

This can be seen in the following example:

var $focusIpt = document.querySelector("#focus-ipt");
$focusIpt.addEventListener("blur", function(e) {
  $focusIpt.value = "Blurred!";
});
setTimeout(function() {
  $focusIpt.focus();
}, 1000);
<input id="focus-ipt" type="text" id="myText" value="Sample Text">
<button type="button">Click me to lose focus</button>

Hope this helps! :)