Search code examples
javascriptkeypress

I want to search using both events: Keypress and Mouse click but they don't seem to be working together


I'm new to Javascript, currently making a weather app. I am trying to make a search using both keypress and click, but it does not seem to work together. I have added two event listeners to the button used for searching. On click seems to work if I comment out the keypress code. As soon as I add the keypress section, I'm unable to make a search using both keypress and click.

const api = {
      key: "48f26e932d82012fa8f78fca8da09da8",
      base: "https://api.openweathermap.org/data/2.5/",
    };
    
    ***const search = document.querySelector(".search");
    const btn = document.querySelector(".btn");
    btn.addEventListener("click", getInput);
    btn.addEventListener("keypress", getInput);
    
    function getInput(event) {
      event.preventDefault();
      if (event.type == "click") {
        getData(search.value);
        console.log(search.value);
      }
    }
    
    function getInput(event) {
      if (event.keyCode == 13) {
        getData(searchbox.value);
        console.log(search.value);
      }
    }***
    
    function getData() {
      fetch(`${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`)
        .then((response) => {
          return response.json();
        })
        .then(displayData);
    }
    
    function displayData(response) {
      // console.log(response);
      if (response.cod === "404") {
        const error = document.querySelector(".error");
        error.textContent = "Please enter a valid city";
        search.value = "";
      } else {
        const city = document.querySelector(".city");
        city.innerText = `${response.name}, ${response.sys.country}`;
    
        const today = new Date();
        const date = document.querySelector(".date");
        date.innerText = dateFunction(today);
    
        const temp = document.querySelector(".temp");
        temp.innerHTML = `${Math.round(response.main.temp)} <span>°C</span>`;
    
        const weather = document.querySelector(".weather");
        weather.innerText = `${response.weather[0].main}`;
    
        const tempRange = document.querySelector(".temp-range");
        tempRange.innerText = ` ${Math.round(response.main.temp_min)}°C / ${Math.round(
          response.main.temp_max
        )}°C`;
    
        const weatherIcon = document.querySelector(".weather-icon");
        const iconURL = "http://openweathermap.org/img/w/";
        weatherIcon.src = iconURL + response.weather[0].icon + ".png";
    
        search.value = "";
      }
    }
    
    function dateFunction(d) {
      let months = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "June",
        "July",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
      ];
      let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    
      let day = days[d.getDay()];
      let date = d.getDate();
      let month = months[d.getMonth()];
      let year = d.getFullYear();
    
      return `${day}, ${date} ${month} ${year}`;
    }

Solution

  • The keypress event fires when a key is pressed inside of that element like for example on an <input> it would fire if you typed inside the input.

    In this case you're adding the listener to the button. In order to get it to register when you want it I'd add it to the search input like so:

    search.addEventListener("keypress", getInput);
    

    Here is a working demo:

    let search = document.getElementById("search");
    let submit = document.getElementById("submit");
    
    
    function getData() {
      console.log("Fetching Data");
    }
    
    submit.addEventListener("click", getData);
    search.addEventListener("keypress", (event) => {
      if(event.keyCode === 13) {
        getData();
      }
    });
    <input type="text" id="search"/>
    <button id="submit">Search</button>