Search code examples
javascriptdomeventskeycode

How to accomplish CTRL + F & CMD + F functionality with Javascript at the same time


I want to enable both ctrl + f & cmd + f with Javascript. So far, I have been able to perform the ctrl + f functionality, but I can't figure out how to enable both.

This is what I have so far:

window.addEventListener('keydown', (e) => {
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        alert('working');
    }
})

This is a code playground.

EDIT 1: Even better if I can run cmd + f on Mac or ctrl + f on Windows.

EDIT 2: I tried the following these answers, but I couldn't make work...


Solution

  • I got it to work like so:

    window.addEventListener('keydown', (e) => {
        if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70) || (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70) || (e.metaKey && e.keyCode === 70))) {
            alert('working');
        }
    })
    

    This is a working code sample.