I want to prevent redo/undo operations in my input box, but when I press cmd+z without focusing on the input box, the text in the input box will still be redo.
// stackoverflow 'Search...' input
const input = document.getElementsByName('q')[0];
input.addEventListener('beforeinput', e => {
if (e.inputType === 'historyUndo' || e.inputType === 'historyRedo') {
e.preventDefault();
console.log('undo/redo prevented');
}
}, { capture: true });
I tried to use document.addEventListener('beforeinput', ...)
, but I cannot distinguish whether the target of the event is my input box. What should I do to prevent it without affecting other input elements?
2
Answers
To prevent Ctrl+Z when the mouse pointer is no longer in the element, you need to monitor keyboard events on your website and check whether the user has pressed Ctrl+Z or not. You can then handle or prevent the undo event depending on your requirements.
Above, I use the keydown event to track when the user presses Ctrl+Z and check whether the mouse pointer is inside the element or not. If the mouse pointer is not inside an element, I suppress the undo event.
The event target is the element upon which the event was done or an element to which the event bubbled. Since you have created an event handler for a specific input, this event handler will not be executed for inputs where this handler was not specified to handle the event. Hence, you do not need to worry about affecting the history of inputs for whom you did not add the event handler. In my example below you can see two inputs, the first has this event handler which overrides history changes and the other has no such event, so its history changes are not overriden.