Here is the code:
<!DOCTYPE html>
<html>
<body>
Input: <input type="text" name="fname" id="fname" onblur="myFunction(this)">
<p>The blur event fires when an element has lost focus.</p>
<script>
function myFunction(ele) {
alert("element has been in blur status, that's why the function is triggered");
ele.focus();
}
</script>
</body>
</html>
MDN: The blur event fires when an element has lost focus.
So when myFunction is triggered, the element has lost focus. then the alert in myFunction will not make it lost focus again (obviously, the element cannot lose one thing it doesn't have).
And alert will block the function until user click the OK button, is it right? After clicking OK button in alert popup, the element still doesn't have the "focus", is it right?
Then ele.focus() will be triggered, now the element have focus again.
But you can try it in jsfiddle, there will be an infinite loop of alert("The onblur event occurs when an object loses focus."), which means onblur event should have been triggered even if you don't do anything.
It's really confusing, what caused the 2nd time onblur event triggered???
It's simple,
because you do not let the element blur. this element is in the focus state until you click on the Alerts "OK" button. After clicking on the "Ok" button it's losing focus and triggers the onblur again It goes to the focus state and shows the alert. Again.....
Simply remove ele.focus(), and it will work as you desire.
I'll try to describe step by step:
onblur calls the myFunction
myFunction executes, which results in opening the alert window
If you leave the ele.focus() inside the function, the focus is
set back on the input element, basically in the same event as the
alert window pops out
You press OK, and the alert window will close
But, since the focus is already back on the input element, the alert window goes in infinite loop, going back to step 1.
If you remove ele.focus() from your code, there won't be 3. and 5. step, and everything will work fine.
<!DOCTYPE html>
<html>
<body>
Input: <input type="text" name="fname" id="fname" onblur="myFunction(this)">
<p>The blur event fires when an element has lost focus.</p>
<script>
function myFunction(ele) {
alert("element has been in blur status, that's why the function is triggered");
}
</script>
</body>
</html>
EDIT: Here is a JS fiddle with console.log included, so you can see that it triggers each time you click OK button.