Search code examples
javascriptapiif-statementweather-api

how can I change this JavaScript to set the background colour


So I have got this code which returns the weather for the location that you have entered.

Instead of it just returning an icon I want it to also change the colour of the background.

I just can't get my head around it all.

function getLocation(){

    var location = document.getElementById("location").value;

    location = location.replace(" ", "%20");

    if (location == ""){

        document.getElementById("location").classList.add("error");

    }
    else {

        document.getElementById("location").classList.remove("error");
        getWeather(location);

    }
}


function getWeather(location){

    var ajax = new XMLHttpRequest();

    var json;


    var apiKEY = "3521a940efd69dc5b6f3dd982d18c618";

    var url = "http://api.openweathermap.org/data/2.5/weather?q=" + location + " ,uk&appid=" + apiKEY;


    ajax.open("GET", url, true);


    ajax.send();


    ajax.onreadystatechange = function(){


        if (ajax.readyState == 4 && ajax.status == 200){

            json = JSON.parse(ajax.responseText);


            document.getElementById("locationForm").style.display = "none";
            document.getElementById("weather").style.display = "block";

            if (json != undefined){

                var weather = json.weather[0].main
                setIconAndDescription(weather, location)

            }
            else {

                description = "Oops, I couldn't find the weather in " + location;
                document.getElementById("description").innerHTML = description;

            }
        }
    }
}

function setIconAndDescription(weather, location){

    var icon;
    var description;

    weather = weather.toLowerCase();

    if (weather == "clear sky"
        || weather == "clear"){

        icon = "clear.svg";
        description = "Yay, sunshine!";

    }
    else if (weather == "few clouds"){

        icon = "few-clouds.svg";
        description = "It's a little cloudy.";

    }

The idea is to use colour theory i.e. red means hot, blue means red and so on.

Any help will would be great,

thanks,

Zack


Solution

  • Do you mean change the backgrund color of the page? In that case just use document.body.style.backgroundColor = "red";