2

I want to create a search bar for my website where it can detect input from the user in the form of typing. How do I start going about this such that when the user starts typing he/she immediately types on the search bar. I am familiar with autofocus, however what I am looking for is automatic redirection upon typing even when the user has clicked something else on the page such that the cursor on autofocus is not on the search bar any more. Is this possible? How does the browser detect typing?

Thanks in advance!

Acrux
  • 386
  • 3
  • 26

3 Answers3

4

I think that you can catch keypress and then set autofocus on your search bar. Something like this

document.onkeypress = function (e)
 {
    document.getElementById("searchBar").focus();
};
2

You can use

document.addEventListener("keypress", setFocus);

Where setFocus is a function that sets the focus to the input field.

function setFocus(){
    document.getElementById("search-field").focus();
}

If you are familiar with jQuery you can use

$( document ).keypress(function() {
  $("#search-field").focus();
});

here is the documentation - keypress

Inside the function you can set the focus on the input field.

Amusing that your search field has an id search-field.

Community
  • 1
  • 1
gyosifov
  • 3,193
  • 4
  • 25
  • 41
  • -1. No need to add JQuery to do this simple job! Besides, you're only addressing the issue on how to capture a keypress, not the issue reggarding focusing the element and writing on it. See my answer for clarification – tfrascaroli Dec 16 '15 at 12:28
  • I'm reverting the -1, and deleting my answer in lieu of this one. Now it's complete :D – tfrascaroli Dec 16 '15 at 12:35
  • @TIMINeutron I believe you may find this funny https://howtodoinjava.files.wordpress.com/2013/04/use-jquery.gif – gyosifov Dec 16 '15 at 12:37
  • OMG.... for real. I agree, JQuery is great, but we shouldn't overuse it, and definitely should not answer a clearly non-jquery answer using the library, unless extremely necessary. And if so, we must first at least introduce the library and explain why we must use it, the OP might have 0 idea what a library is, for all we know. But your answer is complete now ;) – tfrascaroli Dec 17 '15 at 10:19
  • You might want to consider ignoring a few keys outside of the search bar: the cursor and space keys can be used to scroll, when selecting text you can modify the selection with shift + cursor keys. – Gerald Schneider Dec 17 '15 at 10:26
1
     <body onkeydown = "addValue(event)">
        <input type = "text" id = "search" value = ' '/>
        </body> // The body part


     <script>
        var search = document.getElementById ("search");

        function addValue (a){

        search.value+= String.fromCharCode(a.keycode);}
</script>

My attempt :) This will add value regardless of which element has been focused or clicked.

anshabhi
  • 423
  • 6
  • 29