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?
To cause a MouseDown event for a form to occur, press the mouse button in a blank area or record selector on the form. To cause a MouseDown event for a form section to occur, press the mouse button in a blank area of the form section.
Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.
This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.
Definition and UsageThe mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs. Tip: This method is often used together with the mouseup() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With