JavaScript event-handling (propagation/bubbling)

35 Views Asked by At

I've added an event listener to my document, that is listening on keydown. When certain shortcuts, i.e. CTRL+s, is hit, I want something to happen. The problem is that an event is created everytime a key is pressed down, and when the right combination of keys is pressed down ALL the events that are saved up are fired at once.

Example: I have a textbox that the user can write into. Every time they press a key an event is saved. If they write abc into the textbox, then I have three events; a, ab and abc. I only want the last event to be fired, not the first two. The reason this happens, as far as I know, is because of propagation (earlier called bubbling).

What can I do to only fire the last event in the bubble?

My code:

useEffect(() => {
    window.addEventListener("keydown", (event) => {

        if (event.ctrlKey && event.key === "s") {

            var isBtnDisabled = document.getElementsByClassName("flex-none align-middle mb-5").item(0).firstChild.disabled;

            if (!isBtnDisabled)
                Save();

            event.preventDefault();
        }

    }, false
    );
}, [signature]);
0

There are 0 best solutions below