javascriptapiaxiosopenweathermapweather-api

Js function that shows a div as a result of a search but the disappear when something else is searched


Baby developer here. So, I’m creating a weather app using Axios and open weather API to grab live forecast info. I created an empty div in my HTML and then created a function that would show an alert at the bottom of the page ONLY if the city that was searched for has an active weather alert. It works great, the only issue I have is that once I search for a city that has an active alert the alert just stays there, does not disappear unless I refresh the page.
So for example if I search for Paris and paris has an active alert it appears but then if i search for rome and rome does not have an active alert, the paris alert just stays there until I refresh the page

Heres my function: I’m using css html and js only

function showAlerts(response) {
  let alertsElement = document.querySelector("#alerts");
  if (response.data.alerts && response.data.alerts.length > 0) {
    alertsElement.style.backgroundColor = "#981f15";
    alertsHTML = `<div class="alert"> ⚠️ ALERT! ${response.data.alerts[0].event} </div>`;
    alertsElement.innerHTML = alertsHTML;
  } else if (response.data.alerts && response.data.alerts.length < 1) {
    alertsElement.innerHTML = "";
  }
}

Heres a link to the API I’m using and my Git repository

https://openweathermap.org/api/one-call-3

https://github.com/SarahAbousenna/vanilla-weather-application


Solution

  • Thank you all for your answers they really helped!

    I have also tried something that also worked

    I updated the function to >>

    function showAlerts(response) {
      let alertsElement = document.querySelector("#alerts");
      if (response.data.alerts && response.data.alerts.length > 0) {
        alertsElement.style.backgroundColor = "#981f15";
        alertsHTML = `<div class="alert"> ⚠️ ALERT! ${response.data.alerts[0].event} </div>`;
        alertsElement.innerHTML = alertsHTML;
      } else {
        alertsElement.innerHTML = "";
        alertsElement.style.backgroundColor = "#fdf8f4";
      }
    }