Tips for clearing CSS while conducting a subsequent search (eliminating results from the initial search)

I am currently working on a weather application using ES6 which is intended to suggest a song from Spotify based on the current weather conditions and forecast. However, I have encountered an issue where if a user performs consecutive searches for different locations, the app continues to display the song from the initial search.

My current approach involves hiding song tracks in CSS using the 'display: none' property and then toggling their display to 'block' in JavaScript based on the search results using if-statements. I am now seeking a solution to remove the first song displayed from the initial search.

I attempted to replace the if-statements with a switch statement, but it resulted in all songs being hidden. Another idea I have is to utilize classList, although I am unsure of the implementation...

CSS

#musicRain,
#musicClear,
#musicThunderstorm,
#musicSnow,
#musicClouds,
#musicAtmosphere {
  display: none;
}

JS

function showCurrentWeather(response) {
  let currentTemperature = document.querySelector("#currentTemperature");
  currentTemperature.innerHTML = `${Math.round(response.data.main.temp)}°C`;
[etc... ]

if (response.data.weather[0].main === "Clear") {
    document.getElementById("musicClear").style.display = "block";
  }
  if (response.data.weather[0].main === "Drizzle") {
    document.getElementById("musicDrizzle").style.display = "block";
  }
  if (response.data.weather[0].main === "Rain") {
    document.getElementById("musicRain").style.display = "block";
  }
  if (response.data.weather[0].main === "Clouds") {
    document.getElementById("musicClouds").style.display = "block";
  } else {
    document.getElementById("musicAtmosphere").style.display = "block";
  }
}

Answer №1

To ensure that previous settings do not linger, you can reset the display property of each element to either block or none. One way to achieve this is by iterating through an array of weather types and setting the display property based on a condition:

  const weatherTypes = ["Clear","Drizzle","Rain","Clouds","Atmosphere"];
  weatherTypes.forEach( type => {
    const musicType = `music${type}`
    if (response.data.weather[0].main === type) {
      document.getElementById(musicType).style.display = "block";
    }
    else {
      document.getElementById(musicType).style.display = "none";
    }
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Load a webpage using javascript while verifying permissions with custom headers

Seeking guidance as a novice in the world of JavaScript and web programming. My current project involves creating a configuration web page for a product using node.js, with express serving as the backend and a combination of HTML, CSS, and JavaScript for t ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

Choose a region on a scatter plot using JavaScript

My current challenge involves utilizing JavaScript to achieve the following tasks: Create a scatter plot consisting of approximately 10,000 data points Enable users to draw a curved shape on top of the plot in order to select a specific region (The desig ...

Requesting data from the application to the MongoDB database is currently malfunction

Currently, I'm utilizing Express and passport to develop an application. Everything has been going smoothly so far, but I've encountered a problem when attempting to retrieve data from my mongo database. Strangely enough, I am able to successfull ...

The AJAX call to retrieve data from a file dynamically is experiencing issues

I am currently trying to use AJAX to dynamically retrieve data from my PHP page and display it on my HTML page. However, I am running into some issues with getting it to work properly. You can view the page here Here is the snippet from the HTML Page wher ...

The Importance of Avoiding Duplicate Content on a Website

How can we efficiently integrate recurring elements like a navigation menu into all pages of a website? ...

My code seems to be malfunctioning, do you see any issues with it?

When attempting to display blog data based on email, the following code line displayed an error cannot GET /myblog: app.get("/myblog/:e_mail", async (req, res) => { const requestedEmail = req.params.e_mail; try { const user = await Use ...

Comparing the efficiency of AngularJS in generating DOM elements: traditional JavaScript versus jqLite

While working on an AngularJS directive that will display a table with over 1000 rows, my boss advised against using binding due to Angular's limit of around 2000 bindings. Instead, I created the DOM elements dynamically using angular.element(...), wh ...

What is the reason behind window.scrollTo functioning as a cache for the scrollTo value

Currently, I am working on a project using Vue. On the user's homepage, there is a list of posts that are displayed. When the user clicks on "show full post," the list of posts is replaced by an expanded view of the single post. However, a challenge ...

Utilizing Node.js and Express.js to send files with Angular's resource feature

Within my index.html file, I have a button that triggers an Angular service utilizing $resource when clicked. var serviceRest = $resource(URL_API, null, { "connect" : { method: "GET", url: "http://localhost/login"} }); In my expressJS ro ...

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

Is there a way to transform the string representation of a JavaScript object literal into an actual JavaScript object literal?

What is the best method to transform the string... "{ name: 'John' }" ...into a valid JavaScript object literal so I can retrieve data using its keys (e.g. varname["name"] == "John")? JSON.parse() cannot be used because the string is not in val ...

Why is Handlebars {{body}} not rendering my HTML tags properly?

I am perplexed by the fact that the example in the other file is not showing. While working on a CRUD project with Mongo, Express, and Node, I encountered an issue. The code wasn't functioning as expected, so I paused to figure out why. <!DOCTYPE ...

Changing styles with the use of bootstrap.css themes on the fly

I'm experimenting with toggling between a custom dark and light theme in my MVC application. On the _Layout.cshtml page, the default theme is loaded by the following code: <link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original. ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

What is the method for obtaining the angle in a CSS3 rotate transformation?

In my current code, I am setting the rotational angle of an element using the following: $('#1-link-2') .css('height', length) .css('-webkit-transform', 'rotate(' + angle + 'deg) ...

How to remove labels in Highcharts after chart creation or drilldown

My highcharts graph has 2 sets of drill down data in addition to the top level. However, when I reach the last drill down, there can be as many as 100 xAxis categories, making the labels unreadable. To address this issue, I am using the following code snip ...

Node.js script to convert server time to a specific local time

I have this code running on my server-side nodejs for timezone conversion. convertNowToTimezone = (localOffset) => { let d = new Date(); let millis = d.getTime() + (d.getTimezoneOffset() * 60000); //converting server local time to UTC milliseconds ...