Reputation: 394
I have some code that runs on a "blur" event on an element. This code needs to actually use the activeElement, and thus can't actually run from the "blur" event.
I was hoping I could create an event like this. The aim was that the "willblur" event would fire before the "blur" event.
var lastTouchedElement;
$('body').on('click', preBlurHandler);
$('body').on('focusin', postFocusHandler);
$('.inp1').on('willblur', function() {alert('willblur');});
$('.inp1').on('blur', function() {alert('blur');});
function preBlurHandler(ev) {
if (!lastTouchedElement) {
postFocusHandler(ev);
return;
}
var focussingElement = ev.target;
if (lastTouchedElement === focussingElement || $.contains(lastTouchedElement, focussingElement)) {
//focus is staying in the same place, do nothing
return;
}
$(lastTouchedElement).trigger('willblur', [ev, {
target: lastTouchedElement,
focussingElement: focussingElement
}]);
}
function postFocusHandler(ev) {
lastTouchedElement = document.activeElement;
}
The full code is in JSFiddle at https://jsfiddle.net/t0un95jt/3/
But it doesn't work. In fact it's not even close.
Help me StackOverflow; you're my only hope.
Upvotes: 0
Views: 54
Reputation: 394
The key was to use addEventListener instead of JQuery's on(), and to use "mousedown" instead of "click".
instead of this line:
$('body').on('click', preBlurHandler);
I use this:
window.addEventListener('mousedown', preBlurHandler, true);
The final argument for addEventListener: true, means "do this on the capturing phase". The capturing phase starts at the outermost element and works its way through firing an event on subsequent child elements, before the bubbling phase begins which works its way back up the DOM tree.
Upvotes: 1