1

I'm trying to add background image using Javascript CSS property. My code does not work. If I add 'url' directly, it worked. Is 'weatherImage' variable a problem..?

Javascript

var OpenWeatherKey = 'API key';
var locationUrl =  'http://freegeoip.net/json/';

function getLocation(){
    $.ajax({
        url : locationUrl,
        dataType: "json",
        success : function(data){
            var country = data['country_name'];
            var city = data['city'];
            var latitude = data['latitude'];
            var longitude = data['longitude'];
            $('#location').html(city + ', ' + country);
      var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
            getWeather(Weather);

                    }
    });
}
function getWeather(url){
    $.ajax({
        url:url,
        dataType:"json",
        success: function(data){
        var weather = data['weather'][0]['main'];
        var temp = data['main']['temp'];
      var icon = data['weather'][0]['icon'];
      var id = data['weather'][0]['id'];
        document.getElementById('icon').src="http://openweathermap.org/img/w/" + icon + ".png";
        $('#weather').html(weather);
        $('#temp').html(temp);
   // Change F to C, C to F 
  var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
  var celsius = Math.floor((temp)- 273.15) + '\xB0C';


  var $tempDisplay = $("#temp");
  $tempDisplay.html(celsius);
  $("#button-f").on('click', function() {
    $tempDisplay.html(fahrenheit);
  });
  $("#button-c").on('click', function() {
    $tempDisplay.html(celsius);
  });

  // change Background image 
  var imagePhoto = {
    thunder: "http://www.tabinotebook.com/wp-

content/uploads/2017/02/jeremy-bishop-72584.jpg",
        rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
        cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
        snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
        sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg",
  }
  var weatherImage = "";
  function selectImage (id){
  if(id >= 200 && id <= 232){
    weatherImage = imagePhoto.thunder;}
  else if (id >= 300 && id <= 531){
     weatherImage = imagePhoto.rainy;}       
  else if (id >= 600 && id <= 622){
     weatherImage = imagePhoto.snow;}   
   else if (id >= 801 && id <= 804){
     weatherImage = imagePhoto.cloudy;}
  else if (id === 800){
     weatherImage = imagePhoto.sunny;}
  else { 
    weatherImage = imagePhoto.cloudy;}
    }

 // we set the background first after the weatherImage has been assigned a value
    // above
$('body').css('background-image','url(' + weatherImage + ')');


 selectImage(800);
        }
        });
    };



getLocation();

Thank you so much in advance.

3
  • There is no interpolation of variables in JS as there is for example in PHP, i.e. "url($weatherImage)" is legal in PHP. So, do as @Cyclonecode has suggested Commented Feb 19, 2017 at 10:14
  • Where do you call selectImage()? Commented Feb 19, 2017 at 14:53
  • I don't think you should share your api key above =) Commented Feb 19, 2017 at 15:49

1 Answer 1

1

You need to add the actual contents of the variable weatherImage, right now you're just setting the url to the name of the variable. Try changing your code to:

$('body').css('background-image', 'url(' + weatherImage + ')');

It is a little hard to tell what is not working since you don't have included the entire script and you also don't show how and where you call selectImage(). The following should work though:

// change api key to whatever you are using
var OpenWeatherKey = 'your-api-key';
var locationUrl =  'http://freegeoip.net/json/';
var weatherImage = "";
var imagePhoto = {
   thunder: "http://www.tabinotebook.com/wp-content/uploads/2017/02/jeremy-bishop-72584.jpg",
   rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
   cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
   snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
   sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg"
};

function selectImage (id) {
   if(id >= 200 && id <= 232) {
       weatherImage = imagePhoto.thunder;
   }
   else if (id >= 300 && id <= 531) {
       weatherImage = imagePhoto.rainy;
   }       
   else if (id >= 600 && id <= 622) {
       weatherImage = imagePhoto.snow;
   }   
   else if (id >= 801 && id <= 804) {
      weatherImage = imagePhoto.cloudy;
   }
   else if (id === 800) {
      weatherImage = imagePhoto.sunny;
   }
   else { 
      weatherImage = imagePhoto.cloudy;
   }
   // we set the background first after the weatherImage has been assigned a value
   // above
   $('body').css('background-image','url(' + weatherImage + ')');
}

function getLocation(){
   $.ajax({
       url : locationUrl,
       dataType: "json",
       success : function(data){
           var country = data['country_name'];
           var city = data['city'];
           var latitude = data['latitude'];
           var longitude = data['longitude'];
           $('#location').html(city + ', ' + country);
           var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
           getWeather(Weather);
        }
    });
}

function getWeather(url){
   $.ajax({
       url:url,
       dataType:"json",
       success: function(data) {
          var weather = data['weather'][0]['main'];
          var temp = data['main']['temp'];
          var icon = data['weather'][0]['icon'];
          var id = data['weather'][0]['id'];
          document.getElementById('icon').src= "http://openweathermap.org/img/w/" + icon + ".png";
          $('#weather').html(weather);
          $('#temp').html(temp);
          // Change F to C, C to F 
          var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
          var celsius = Math.floor((temp)- 273.15) + '\xB0C';
          var $tempDisplay = $("#temp");
          $tempDisplay.html(celsius);
          $("#button-f").on('click', function() {
             $tempDisplay.html(fahrenheit);
          });
          $("#button-c").on('click', function() {
             $tempDisplay.html(celsius);
          });

          // select background image based on id
          selectImage(id);
       }
   });
};

getLocation();
Sign up to request clarification or add additional context in comments.

12 Comments

$('body').css('background-image','url(' + weatherImage + ')'); }
@aaayumi- You must include the whole script and also show where and how you're calling selectImage(). A quick solution would be to move the actual background assignment to the bottom om the selectImage() function.
@aaayumi - I added a working example that uses jquery.
I added selectImage() function.. still does not work. I added a full script as well..
Thank you so much. I compared your code and my code. My code was so disorganized..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.