Command K Web Component 💻

A web component that opens a search box when you press Command + K on your keyboard.

Press   Command + K   to try it out. ⌨️

How it Works

This page has a web component that is loaded in the <command-k> tag. The web component is loaded from the commandk.js file.

This web component opens a dialog box when you press Command + K on your keyboard. The dialog box has a search field and a list of search results.

The list of search results is retrieved by executing a function called searchFunction. This function is passed the search field and the shadow root of the web component.

This function is kept separate from the web component so that you can define the search logic separately in your application.

The web component is styled by taking all tags in a <template> tag and adding them to the shadow root of the web component.

Set it Up

First, download the commandk.js file and add it to your project.

Then, add the following script tag to your page.

<script src="commandk.js"></script>

Then, add the <command-k> tag to your page.

<command-k></command-k>

Finally, define the searchFunction function.

function searchFunction(searchField, shadowRoot) {
    // Use the query to add li elements to the shadow root
}
            

Search Function Examples

Query a JSON API

function searchFunction (searchField, shadowRoot) {
fetch(`http://localhost:3001/search?q=${searchField.value}`)
    .then((response) => response.json())
    .then((data) => {
        data.forEach((result) => {
            const li = document.createElement('li');
            const a = document.createElement('a');
            a.href = result.url;
            a.innerText = result.title;
            li.appendChild(a);
            shadowRoot.querySelector('#command-k-search-results').appendChild(li);
        });
    });
}
            

Search Through a List of JSON Objects

function searchFunction (searchField, shadowRoot) {
    var docs = [
        {
            "title": "Command K Web Component",
            "url": "https://commandk.jamesg.blog"
        }
    ]

    var results = [];

    for (var i = 0; i < docs.length; i++) {
        if (docs[i].title.toLowerCase().includes(searchField.value.toLowerCase())) {
            results.push(docs[i]);
        }
    }

    for (var i = 0; i < results.length; i++) {
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.href = results[i].url;
        a.innerText = results[i].title;
        li.appendChild(a);
        shadowRoot.querySelector('#command-k-search-results').appendChild(li);
    }
}