0

I am writing a front-end web app that provides weather conditions for the user's location. While the basic functionality is working, at the moment I'm trying to write the logic that allows the app to change the background of the body based upon the current weather conditions. To do this, I'm making use of the OpenWeatherMap API. A call to this API returns a JSON response, and among the many things returned, are two fields - id and icon. id returns a numerical code which determines the weather condition, like clear skies or broken clouds, and icon returns a string which determines if it's day or night.

To write the logic, I created a JS object which would have the id condition codes as the keys and the corresponding images as the values. Inside the .ajax() function, I have a switch block, where I switch based on the id returned, and then use .css("background-image", "url(link)"); to set the background-image of the body.

The issue with the code is that - this way the browser doesn't seem to recognise the URL to the background-image. I see a GET - ... 404 not found error in the console. However, if instead of trying to access the URL to the image through the JS object, if I directly place the url to the image in .css(), it works. But of course that's not what I want.

Here's the JS object -

//object for images
var weatherConditions = {

    //Group 2xx: Thunderstorm
    '2xx' : 'http://www.weathersnapshot.com/wp-content/uploads/2014/04/414.jpg',    

    //Group 3xx: Drizzle
    '3xx' : 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSsE4vZDsOCCsuE9X2WljNm0VewUdFj7onj438c9mD3_I6AfT71sA',

    //Group 5xx: Rain
    '5xx' : 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSsAlLmRls8CtL994qiwssqvQwdMNEI7yJcUUPWqNhMdtjGHExK',

    //Group 6xx: Snow
    '6xx': 'https://dl.dropbox.com/s/sywq7fk1u65lycf/6810006-snow-background.jpg?dl=0',

    //Group 800: Clear - day and night
    '800': ['https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTnYxZWx1uOc83uWxrTFfW7IiVj0XXMKM6fSdqS9U5kjh7Op_71WA', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQnSe0ASBAUAcsvEAkQqO28WFGCjLWAgODq9eosh2SBr9f4-_NI4Q'],

    //Group 80x: Clouds - day and night
    '8xx' : ['https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ_Fl9xNhT3AVwafZ2GeciqaqdLXosI-nPfhrVGvM7QFO0z0KQa', 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTgvOYSdZ7tHUybUfF5ydC2G97i78pv3hZ8jlX632lCu26VABGs3Q']


};

Note - I've tried hosting the images on dropbox too, as I thought the errors might be due to the image links themselves. But it had no effect.

This is a part of the switch block -

//---------get background-----------------
      var weatherID = data.weather[0].id;
      console.log("Weather ID = " + weatherID);

      switch(weatherID) {
        case 600: console.log(weatherConditions['6xx']);
                  $("body").css("background-image", "url(weatherConditions['6xx']");
                  break;
        case 800: console.log("inside clear sky weather");
                    $("body").css("background-image", "url(weatherConditions.8xx[0])");
                  break;
        case 803: //check for day or night
                  if(data.weather[0].icon.endsWith("d")) {
                    console.log("inside day weather");
                    $("body").css("background-image", "url(weatherConditions['8xx'][0])");
                  }
                  break; 
        case 804: $("body").css("background-image", "url(http://www.weathersnapshot.com/wp-content/uploads/2014/04/414.jpg)");
      }

And here's the Pen with the full code.

1 Answer 1

1

"url(weatherConditions['6xx']" is exactly what it looks like. There is no substitution happening there, you're telling the browser to use weatherConditions['6xx'], literally, as the URL. (You're also missing the ) on that.)

You probably wanted to substitute:

$("body").css("background-image", "url(" + weatherConditions['6xx'] + ")");

In ES2015 (which you can use today with transpiling, and in months/a year/something without tranpiling) you could use a template string (quoted with backticks, using ${...} for placeholders):

$("body").css("background-image", `url(${weatherConditions['6xx']})`);

Here's an example using our Gravatars:

var gravatars = {
  "Manish": "https://www.gravatar.com/avatar/4657faf6aa5c4b2c01ce4fb6c63300ed?s=164&d=identicon&r=PG",
  "T.J.": "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=164&d=identicon&r=PG"
};
$("input[type=button]").on("click", function() {
  $(".holder").css("background-image", "url(" + gravatars[this.value] + ")");
});
.holder {
  display: inline-block;
  width: 164px;
  height: 163px;
}
<input type="button" value="Manish">
<input type="button" value="T.J.">
<div>
  <div class="holder"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks!! I was under the impression that since it's an object, putting in the key would substitute in the URL directly, but it makes sense now. And did you mean the ES6 update when you mentioned ES2015? Also, is the template string the same as Django Templates? Something like {% block content %}. If so, then I think I understand what you mean.
@Manish: ES2015 is the official name of "ES6" (I usually write "ES2015 (aka ES6)", seem to have forgotten above.) ES2015's template strings are similar to a very limited version of several templating libs, but are much smaller in scope (no looping constructs, etc.).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.