Reputation: 3821
I tried following code to intercept mousedown
event and then to re-dispatch it in order to get under control whenever any element gains focus.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('mousedown', function (e) {
console.log('mousedown', e);
if (e.target.getAttribute('id') === 'target' && !e.__redispatched) {
console.log('cancelling');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
setTimeout(function () {
var re = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
view: window,
screenX: e.screenX,
screenY: e.screenY,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
altKey: e.altKey,
button: e.button,
buttons: e.buttons,
relatedTarget: e.relatedTarget,
region: e.region
});
re.__redispatched = true;
document.getElementById('target').dispatchEvent(re);
}, 100);
}
})
</script>
<input id="target" type="text"/>
</body>
</html>
Console shows that event is properly re-dispatched, because it's captured by target
element, but focus is not gained to that element.
When I try that without meddling into events, focus is gained right before mousedown
event is processed.
Is it possible to handle this behavior just by re-dispatching mousedown
event or do I have to manually process focus
?
Or do I do something wrong with the event?
Upvotes: 5
Views: 1483
Reputation: 333
The focus
is triggered after receiving the mousedown
event. However the browser does not run default handlers for untrusted events such as MouseEvent
fired using dispatchEvent
.
You have to focus
the input manually.
Upvotes: 7