Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotkey for opening the search #38

Closed
Zamiell opened this issue Feb 6, 2021 · 3 comments
Closed

Hotkey for opening the search #38

Zamiell opened this issue Feb 6, 2021 · 3 comments

Comments

@Zamiell
Copy link

Zamiell commented Feb 6, 2021

With Algolia, you can press Ctrl+K to handily open the search bar.
With docusaurus-lunr-search, there is no such hotkey available, to my knowledge.

Is this something that can be added? I guess it would just a bit of passive JavaScript that listens for this particular keystroke, and then puts the focus in the search bar.

@Zamiell
Copy link
Author

Zamiell commented Feb 6, 2021

In the meantime, this is what I came up with:

hotkey.js

// In order for the search box to initialize properly, we have to manually click it
document.addEventListener('DOMContentLoaded', function() {
  const search = document.getElementById('search_input_react');
  search.click();
});

// Ctrl + K should focus the search bar, emulating the Algolia search UI
document.onkeydown = function(e) {
  if (e.ctrlKey && e.key == 'k'){
    const search = document.getElementById('search_input_react');
    search.focus();

    // By default, using Ctrl + K in Chrome will open the location bar, so disable this
    e.preventDefault();
  }
}

To enable it, you put it in the scripts section of docusaurus.config.js.

@kamtschatka
Copy link

Thanks for providing the code.
One thing that is not really mentioned is the fact that the search does not initialize until the field is hovered over, which causes it to show "Loading..." all the time.
Would be nice to have that initialized once the page finished loading.

I have tried your script, but clicking the element does not work and additionally when DomContentLoaded is fired, the element is not on the page yet, so I have switched to setInterval and firing mouseover:

let intervalId;

function initializeSearchBar() {
    let searchbar = document.getElementById('search_input_react');
    if (searchbar) {
        let event = new MouseEvent('mouseover', {
            'view': window,
            'bubbles': true,
            'cancelable': true
        });

        searchbar.dispatchEvent(event);
        clearInterval(intervalId);
    }
}

setInterval(initializeSearchBar, 500);

@praveenn77
Copy link
Owner

Added in new version 3.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants