How to trigger an input with type file using your keyboard

Let's assume that you have the following component:

html
<input onchange = 'upload()' id = 'upload' type = 'file' multiple/>

The input will open a dialog box to select multiple files on click.

If you want to open the dialog using your keyboard, for example, by pressing ctrl + U, you can create the following listener:

javascript
const onDown = (e) => {

    if(e.ctrlKey && e.key === 'u'){
                
        e.preventDefault();
                
        document.getElementById('upload').click();
                
    }
}

window.addEventListener('keydown', onDown);

This will simulate a click on the input that you have previously created.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.