Trigger search box using keyboard

You must've came across websites using specific keyboard shortcuts to trigger the search box, for ex - tailwindcss.com, bootstrap and github.com

search tailwind.png

search github.png

here you can use "ctrl + k" or "/" to trigger the search bar.

Let's see how to implement this using JavaScript.

Html

<div class="search">
    <div>
        <input type="text" id="search-box" placeholder="Ctrl + k">
    </div>
</div>

CSS

Style the search bar.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

input {
    width: 12rem;
    height: 1.5rem;
    padding: 1rem 0.5rem;
    border: 3px solid rgb(183, 176, 176);
    border-radius: 5px;
}

textarea:focus,
input:focus {
    outline: none;
}

::placeholder {
    opacity: 0.6;
    font-family: 'Gill Sans', sans-serif;
    font-size: 17px;
}

input:focus {
    transform: scale(1.02);
    border: 3px solid #000;
}

.search {
    position: relative;
}

JavaScript

document.addEventListener("keydown", (e) => {
    e = e || window.event;
    const searchbox = document.getElementById("search-box");
    // ctrl k
    if (e.ctrlKey && e.key === "k") {
        searchbox.focus();
        e.preventDefault();
    }
});

you can do the same thing for "/" as well just change the if condition and give it a shot.

If you found it helpful please do consider a follow, like and comment down below.

Β