Help with if/else statement in weather app

I’m having a little a trouble getting an if/else statement to work to change the background dependent on the summary of the weather for a weather app that I’m working on. The statement is at the bottom of the code. I console logged the api for the weather data so you can see it. What I’m trying to target is the daily summary.

https://weather-me.netlify.com


window.addEventListener('load', () => {
    let long
    let lat
    const temperatureDescription = document.querySelector('.temperature-description')
    const temperatureDegree = document.querySelector('.temperature-degree')
    const locationTimezone = document.querySelector('.location-timezone')
    const temperatureSection = document.querySelector('.temperature')
    const temperatureSpan = document.querySelector('.temperature span')
    const dailyDescription = document.querySelector('.daily-description')
    const mon = document.querySelector('.mon')
    const tues = document.querySelector('.tues')
    const wed = document.querySelector('.wed')
    const thurs = document.querySelector('.thurs')
    const fri = document.querySelector('.fri')
    const sat = document.querySelector('.sat')
    const sun = document.querySelector('.sun')


    if(navigator.geolocation){
        //if user allows location access 
        navigator.geolocation.getCurrentPosition(position => {
            //run function to get latitude and longitude of user
            long = position.coords.longitude
            //set longitude coordinates to a variable
            lat = position.coords.latitude
            //set latitude coordinates to a variable

            const proxy = 'https://cors-anywhere.herokuapp.com/'
            const api = `${proxy}https://api.darksky.net/forecast/edb3046b24065a7cbfda5603a675cbf9/${lat},${long}`;
            //set api key as a variable and input lat and long variables using template string

            fetch(api) //do a get request from the api url 
            .then(response => {
                return response.json()
            }) //retun the response to json
            .then(data => {
                console.log(data) //long the weather data returned from the api
                const {temperature, summary, icon} = data.currently //pull temperature from data.currently

                //set DOM elements from the API
                temperatureDegree.textContent = Math.floor(temperature)
                temperatureDescription.textContent = summary
                locationTimezone.textContent = data.timezone
                dailyDescription.textContent = data.hourly.summary

                // Set weekly elements fromt the DOM
                mon.textContent = data.daily.data[0].icon
                tues.textContent = data.daily.data[1].icon
                wed.textContent = data.daily.data[2].icon
                thurs.textContent = data.daily.data[3].icon
                fri.textContent = data.daily.data[4].icon
                sat.textContent = data.daily.data[5].icon
                sun.textContent = data.daily.data[6].icon


                //Set Icon
                 setIcons(icon, document.querySelector('.icon'))
                
                //Formula for Celsius
                let celsius = (temperature - 32) * (5 / 9)
                   

                //Change temperature to celsius/fahrenheit
                temperatureSection.addEventListener('click', () => {
                    if (temperatureSpan.textContent === 'F') {
                        temperatureSpan.textContent = 'C'
                        temperatureDegree.textContent = Math.floor(celsius)
                    } else {
                        temperatureSpan.textContent = 'F'
                        temperatureDegree.textContent = Math.floor(temperature)
                    }
                })
            })
        })

        function setIcons(icon, iconID) { //run function to take the icons from currently object and match them with skycons
            const skycons = new Skycons({color: "white"}); //Set var and properties for skycons
            const currentIcon = icon.replace(/-/g, "_").toUpperCase() // look for every line in the currently object and replace with _ to match skycons icon
            skycons.play() //make skycons animation play
            skycons.set(iconID, Skycons[currentIcon]) //set the icon to current icon to run in function
        }

    } 

    if (summary = "Overcast" || "Mostly Cloudy") {
        document.body.style.background = "url('https://images.unsplash.com/photo-1534088568595-a066f410bcda?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=689&q=80')"
    } else if (summary = "Partly Cloudy") {
        document.body.style.background = "url('https://turntable.kagiso.io/images/partly-cloudy-1173077-639x447.width-800.jpg')"
    } else if (summary = "Drizzle" || "Light Rain") {
        document.body.style.background = "url('https://images.unsplash.com/photo-1534088568595-a066f410bcda?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=689&q=80')"
    } else if (summary = "Sunny"){
        document.body.style.background = "url('https://images.unsplash.com/photo-1531147646552-1eec68116469?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80')"
    } else {
        document.body.style.background = "url('https://images.unsplash.com/photo-1531147646552-1eec68116469?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80')"
    }
})

Right under the .then to pull the data from the API.

Sorry, I should’ve included a link. https://weather-me.netlify.com/

Thank you very much. I will look over these challenges. I didn’t even think about the equality operators, thank you!

But yes, as for the images, I’m just using fillers for now to get the statements correct.

Thanks again!

Thank you, I’d really appreciate it! I’m going to work on it tomorrow after work. I’ll share an update then.

Hi Randell, I just wanted to give you an update and see if you could point me in the direction for improvement.

I moved the if/else statements to the correct scope, so they’re within the then callback. I also recognize that I wasn’t using the correct equality operator, and I wasn’t correctly making comparisons within the if statements. I was saying

if (summary == "cloudy" || "overcast")

rather than

if (summary == "cloudy" || summary "overcast")

So that gave me a working solution. However, I was looking further at the darksky documentation and found that it would not be wise to use ''summary" for something like trying to set the background dependent on weather. Here’s their explanation:

The algorithm that generates a human-readable summary is complex and can produce millions of possible summaries—too many to be practical for automated processing. Moreover, we’re constantly tweaking the logic, so any pattern-matching you do against our summaries today could easily break tomorrow! By contrast, we promise to keep the values of icon property documented and warn you of any changes to that list.

So I’ve since updated the if/else statements to be dependent on the icon property. I plan to add them all in the future, but I just wanted to hear your inputs and suggestions before proceeding with anything.

Thanks again! Here’s the code and a link to the the live site:



window.addEventListener('load', () => {
    let long
    let lat
    const temperatureDescription = document.querySelector('.temperature-description')
    const temperatureDegree = document.querySelector('.temperature-degree')
    const locationTimezone = document.querySelector('.location-timezone')
    const temperatureSection = document.querySelector('.temperature')
    const temperatureSpan = document.querySelector('.temperature span')
    const dailyDescription = document.querySelector('.daily-description')
    const mon = document.querySelector('.mon')
    const tues = document.querySelector('.tues')
    const wed = document.querySelector('.wed')
    const thurs = document.querySelector('.thurs')
    const fri = document.querySelector('.fri')
    const sat = document.querySelector('.sat')
    const sun = document.querySelector('.sun')


    if(navigator.geolocation){
        //if user allows location access 
        navigator.geolocation.getCurrentPosition(position => {
            //run function to get latitude and longitude of user
            long = position.coords.longitude
            //set longitude coordinates to a variable
            lat = position.coords.latitude
            //set latitude coordinates to a variable

            const proxy = 'https://cors-anywhere.herokuapp.com/'
            const api = `${proxy}https://api.darksky.net/forecast/edb3046b24065a7cbfda5603a675cbf9/${lat},${long}`;
            //set api key as a variable and input lat and long variables using template string

            fetch(api) //do a get request from the api url 
            .then(response => {
                return response.json()
            }) //retun the response to json
            .then(data => {
                console.log(data) //long the weather data returned from the api
                const {temperature, summary, icon} = data.currently //pull temperature from data.currently

                //set DOM elements from the API
                temperatureDegree.textContent = Math.floor(temperature)
                temperatureDescription.textContent = summary
                locationTimezone.textContent = data.timezone
                dailyDescription.textContent = data.hourly.summary

                // Set weekly elements fromt the DOM
                mon.textContent = data.daily.data[0].icon
                tues.textContent = data.daily.data[1].icon
                wed.textContent = data.daily.data[2].icon
                thurs.textContent = data.daily.data[3].icon
                fri.textContent = data.daily.data[4].icon
                sat.textContent = data.daily.data[5].icon
                sun.textContent = data.daily.data[6].icon


                //Set Icon
                 setIcons(icon, document.querySelector('.icon'))
                
                //Formula for Celsius
                let celsius = (temperature - 32) * (5 / 9)
                   

                //Change temperature to celsius/fahrenheit
                temperatureSection.addEventListener('click', () => {
                    if (temperatureSpan.textContent === 'F') {
                        temperatureSpan.textContent = 'C'
                        temperatureDegree.textContent = Math.floor(celsius)
                    } else {
                        temperatureSpan.textContent = 'F'
                        temperatureDegree.textContent = Math.floor(temperature)
                    }
                })

                //Set background dependent on weather
                if (icon== "cloudy") {
                    document.body.style.background = "url('https://images.unsplash.com/photo-1479688895406-3f032f15f0ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80')"
                } else if (icon == "partly-cloudy-day") {
                    document.body.style.background = "url('https://turntable.kagiso.io/images/partly-cloudy-1173077-639x447.width-800.jpg')"
                } else if (icon == "rain") {
                    document.body.style.background = "url('https://images.unsplash.com/photo-1417008914239-59b898b49382?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1364&q=80')"
                } else if (icon == "sunny" || icon == "clear-day"){
                    document.body.style.background = "url('https://images.unsplash.com/photo-1531147646552-1eec68116469?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80')"
                } else {
                    document.body.style.background = "url('https://images.unsplash.com/photo-1531147646552-1eec68116469?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80')"
                }


            })
        })

        function setIcons(icon, iconID) { //run function to take the icons from currently object and match them with skycons
            const skycons = new Skycons({color: "white"}); //Set var and properties for skycons
            const currentIcon = icon.replace(/-/g, "_").toUpperCase() // look for every line in the currently object and replace with _ to match skycons icon
            skycons.play() //make skycons animation play
            skycons.set(iconID, Skycons[currentIcon]) //set the icon to current icon to run in function
        }

    } 
})

https://weather-me.netlify.com/

Thank you Randell. That makes a lot of sense to simplify the setting of the background by setting it with css classes. I’m guessing it’s also more performant to do it that way instead of in the JS? I also plan to download the images so it isn’t fetching from a URL each time.

If you check the link again, you can see how I took the date from the daily object and added it to the weekly div. I realized that it wouldn’t make sense to name the divs the days of the week, since I want that section to show the next six days, rather than mon - sun each time. So I named them oneDayFromNow, twoDaysFromNow etc.

I would be interested to hear your thoughts on that. I just added them with javascript for practice. I’m not sure if it would be better to added the divs with html first then just set the content with javascript.

I will also implement the changes you’ve showed me. I really appreciate the guidance!

Hi Randell, I’m having some trouble getting the the setBackground function to work while removing the if else statements and using CSS to change the background image. Any idea what I’m doing wrong? I’ve been over it a few times but can’t figure it out.

I wanted to get that right before I moved on with the other changes.

https://weather-me.netlify.com

Hmm. I guess I’m not understanding. Shouldn’t it be called immediately because icon is already set from data.currently?

Oh duh, I see. I just need to call it right after, passing in icon.

Hi @camperextraordinaire, sorry to bother you again. I have another question if you get time. I reworked some of my code to make it more readable. Mostly, I added spans in the HTML that contain the day of the week and the high and low temperatures. Along with adding the icons for each day. I still need to refactor it all though, which I plan to do after I figure out this last issue.

I noticed that since added these spans, the fuction setBackground no longer works. I’m thinking it has something to do with this:Node: textContent property - Web APIs | MDN

Setting textContent on a node removes all of the node’s children and replaces them with a single text node with the given string value.

Because on that function I set document.body.className = backgrounds[icon] || 'bg-default';
after setting the textcontent of those spans. But I’m not sure if there’s any way around it.

Thanks!

Wow it’s working for me now too. I have no idea how that happened after I didn’t change anything.

I guess the next thing then, would be for me to refactor the section where I set the day/icon/high and low.

Do you know of any resources you could send for where to start with that?