javascriptdom-eventskeycodesearch-box

Vanilla Javascript: How do I create a working searchbar with hidden results?


I am pretty new to Javascript and have been using it for almost a month. I am trying to create a website easter egg that can be found by typing a hidden word into the searchbar. My problem mostly has to do with making the variable value read the strings in the array. There were no error messages that popped up.

Here is my code:

let searchResults = ['dog', 'cat', 'bird'];
let searchInput = document.querySelector('.search-box .input-box #searchbar');

function searchBar() {
  searchInput.addEventListener("keyup", function(event) {
    if (event.keyCode == 13) {
    } else {
    }
    });
  searchInput.addEventListener("input", function(event) {
    let value = event.target.value;
    if (value == searchResults[2] && (event.keyCode == 13)) {
      window.location.href = "bird.html";
    } else {
    }
  });
}

There is also a small additional issue with the keycode firing off multiple times. I'm not too worried about this, but it would be nice to find a solution for it.


Solution

  • There is no "keyCode" property for an input event. The keyCode exists only on keyboard events, but input is it's own, separate type of event.

    Use the keyup event instead. There's really no reason to have two separate event handlers anyway.

    let searchResults = ['dog', 'cat', 'bird'];
    let searchInput = document.querySelector('#searchbar');
    
    
    searchInput.addEventListener("keyup", function(event) {
      if (event.keyCode == 13) {
        
        let value = event.target.value;
        if(value == searchResults[2]){
        
          // window.location.href = "bird.html";
          console.log("birb");
        
        }else{
        
          // User hit enter but it wasn't bird...
        }
        
      }
    });
    <input id=searchbar>