In onblur
I need to call alert()
, but this doesn't work in Chrome and Firefox. Sess https://jsfiddle.net/mimomade/5sur482w/1/
In Firefox :focus-visible
stays after leaving the 2nd and 4th input field and is not removed.
In Chrome I can't leave the 2nd input field. Although the 1st doesn't has any problem.
At the very bottom is the code with both bugs fixed. You're initial JavaScript looks like this:
// Has different bugs in Firefox and Chrome.
function blurring(el) {
console.log(el.id + ' pre alert');
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}
In Firefox, your apparent bug actually masks a bug similar to what you're encountering in Chrome. When the alert is removed, the code has the intended behavior, so alert and the event are interacting in a weird way. In this specific case, to get around this, we can just wait for the event to finish by wrapping the function in a zero-millisecond timeout.
// Has a similar bug in both browsers.
function blurring(el) {
console.log(el.id + ' pre alert');
setTimeout(function () {
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}, 0);
}
In Chrome, your bug appears to be caused by the blur event emitting each time the alert box is closed. Luckily, because we wait for the events to finish, the active element should be the element newly selected input instead of whatever the browser set it to. This means checking ensuring el
and document.activeElement
are different is sufficient to fix this bug.
// addresses both bugs.
function blurring(el) {
console.log(el.id + ' pre alert');
setTimeout(function () {
if (document.activeElement !== el) {
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}
}, 0);
}