Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable.

I am struggling with how to update the background dynamically depending on the weather condition.

Thank you for your help!


displayalerts(){
    let weather = this.state.cond;

    let alerts;

    if (weather === "Snow")
    {
        alerts = ["check tire tread and pressure", "maintain safe stopping distances", "steer gently into skids"];
    }
    else if (weather === "Rain")
    {
        alerts = ["steer gently into skids"];
    }
    else if (weather === "Mostly Cloudy")
    {
        alerts = ["maintain safe stopping distances", "turn on fog lights"];
    }
    else if (weather === "Overcast")
    {
        alerts = ["check lights", "turn on fog lights"];
    }
    else if (weather === "Haze")
    {
        alerts = ["turn on fog lights"];
    }
    else if (weather === "Partly Cloudy")
    {
        alerts = ["check lights"];
    }
    else if (weather === "Sunny" || weather === "Clear")
    {
       

        alerts = ["Use the air conditioning"];
        
    }
    else {
        alerts = ["No alerts available"];
    }
.container {
width: 414px;
display: flex;
flex-direction: column;
background-image: url('http://bestanimations.com/Nature/winter/winter-snow-nature-animated-gif-23.gif');
background-attachment: fixed;
    background-size:cover;
color: #fff;
margin: 0 auto;
font-family: acumin-pro-condensed, sans-serif;
font-style: normal;
font-weight: 100;
}

Answer №1

For styling inline, you can utilize the following code snippet:

const weatherToImage = {

  "hot" : "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEBUQEhIVFRUWFhUVFRUVFRUVFRcVFxYWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGy8mHyAvLy0rMi0tLS01LS0vLS0tLS0tLS0tLS0tLS0wLi0vLS0tLS0tLS0tLy0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAAAAQIDBAUGBwj/xAA7EAABAwMCBAQEBQIFBAMAAAABAAIRAxIhBDEFQVFhBhMicTKBkaEjscHR8EJSBxRigvFystLhFTND/8QAGgEAAwEBAQEAAAAAAAAAAAAAAAEDAgQFBv/EAC0RAAICAQMCBAUFAQEAAAAAAAABAhEDBBIhMUEFExRRMnGh0fAigZGx4WEV/9oADAMBAAIRAxEAPwDsHvlU6zVQZrzzVmnXuXXtOW7HNCs08KFoyrACALFHVNG7S6egUwpiZG3RQUagCKtR1wjb81mjVlpvVTeZHNVxVCjfWkpUBefrUw63oqDqoVHW8WpU2lz3hsfp2WowsTmYviyuNKHVgSPMfy/uOTj5LzHietdWqGo6JPRbPi/j51VSGn8NsQOruZ+652F6mHHtjz1IN8jSEkJ8IhVEMhCdCIRQDIRCdCIRQWNhEJ0IhFDsZCIT4SQigsZCIT4SQigsbCE6EQlQ7GoToRCKAbCIT4Wlp/D+qe29tB9pEzECO...

You can view a working demo here

Answer №2

Is this the kind of thing you're looking for?

document.querySelector(".wrapper").style.backgroundImage = 'url(http://..'+condition+'.jpg)';

The URL provided is simply a placeholder, utilizing the condition variable.

Answer №3

To eliminate the background-image property from the CSS, you can include this line of code for each if statement:

document.querySelector(".container").style.backgroundImage = "url('http://bestanimations.com/Nature/winter/winter-snow-nature-animated-gif-23.gif')";

This should be done with the appropriate link related to weather.

However, I believe this approach is hard-coded...

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

Tips for maintaining position when refreshing a web page within a scrolling table

Recently, I came across a helpful tutorial on how to create a table with a fixed header and scrollable body. You can find it here. While the tutorial worked perfectly for me, I encountered an issue when trying to refresh the webpage and maintain my positio ...

Customizing the Autocomplete Tag in Material UI: A Step-by-Step Guide

Currently, I am utilizing material ui's autocomplete feature and this is how the default tag appears. https://i.stack.imgur.com/PKorz.png My goal is to create a customized tag like this: https://i.stack.imgur.com/DLY1w.png Could someone please adv ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

How can I incorporate a custom icon into the <i> tag in HTML like Bootstrap does with its icons?

When working with Bootstrap, you can easily add an icon using the following syntax: <i class="bi bi-arrow-right-square-fill fs-1"></i> One great feature is that you can adjust the size of the icon by simply adding the fs-1 class. If ...

javascript - Retrieving a JSON string

I am currently working on a stock website where I need to retrieve JSON information from either Google's API or Yahoo's API. To test this functionality, I have used a replacement function to log the data onto a text box for testing purposes. Howe ...

Unlocking numerical input solely by executing the specified command within the most up-to-date iteration of the Chrome Extension of Selenium IDE

After executing the command in Selenium IDE, I successfully extracted the sentence, "Your booking ID is 1234", and saved it in a variable named myText. <table> <tr> <th>Command</th> <th>Target</th> < ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Is there a way to make my red div switch its background color from red to green when I press the swap button?

How can I make the red div change its background color to toggle between red and green when I click on the swap button in the following code? $(document).ready(onReady); var numberOfClicks = 0; function onReady() { console.log('inside on ready ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

Navigating Websites in Google Search

Whenever I search for keywords related to my website on Google, the search results show my website's content and address. However, when I click on the link, it redirects me to a different unrelated website. Click here to view an image ...

`When utilizing $routeParams, the CSS fails to load`

Whenever I use parameters in ngRoute and go directly to the URL (without clicking a link on the site), the CSS fails to load. All my routes are functioning properly except for /chef/:id. I utilized yeoman's angular generator, and I am running everythi ...

Conceal the Slider until Fully Loaded with Slick Slider by Ken Wheeler

I am currently using a slider function called Slick by Ken Wheeler. It is currently being loaded in the footer with just two variables. $('.slickSlider').slick({ dots: true, fade: true }); Currently, ...

Conditionally inject snippets of styling based on the emotion styling approach

I have a styled component: const StyledBox = styled(Box)(({theme, locked}) => ({ width: theme.spacing(2.5), height: `calc(50% - 12px)`, borderColor: grey[500], borderStyle: 'solid', borderWidth: 0, borderLeftWidth: 3, ...

The drop-down links vanish into the depths of the webpage's body

Can someone assist with my drop-down menu issue for the link "services"? The link disappears behind the page content when I try to modify it. Any help would be appreciated, thank you! This is the CSS: .bodycontent { margin: 0 25% 0 25%; ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Modify dates on constant URL and run the link

I've got a link that looks like this: Is it possible to create an HTML form with two input date fields and merge them into a single link similar to the one above? I want to select dateFrom and dateTo separately, then click GO to access the link. I&a ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...

Creating a Composite of Several Boxes in THREE.js

My goal is to display multiple boxes together in a specific structure shown in the image I have attached. I am interested in testing the GPU limitations by increasing the number of boxes, and then later on, I will focus on optimization. The framework I am ...

Strategies for sorting data in d3js/dimplejs visualizations

I am looking to enhance the interactivity and responsiveness of a d3js/dimplejs chart by implementing filtering based on clicks in the legends for different series. The code I tried below did not hide the series as expected, although it worked well with a ...

Tips for implementing an onclick jquery function within an input field

Just starting out with JavaScript and jQuery, I have a jQuery function that looks like this: $('.input-group .date').datepicker({ }); I want to apply it to the following HTML structure: <div class="input-group date" id="dp3"> <inp ...