Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable?

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 for your help.

Answer №1

If you want the actual content of the variable weatherImage to be added, then you need to update your code. Currently, you are just setting the URL to the name of the variable. Try changing your code snippet to:

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

It's a bit tricky to pinpoint what exactly isn't working since we don't have access to the full script and aren't sure where or how you call selectImage(). However, the following modified code should function properly:

// Modify the API key according to your requirements
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;
   }
   // Set the background once weatherImage is assigned a value
   $('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);
          // Convert temperature units from F to C and vice versa 
          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);
          });

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

getLocation();

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

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

The "hover" effect is not activating on a carousel

I'm having trouble with the hover effect inside the orbit slider. It's not working at all. What am I missing here? Check out the code and fiddle: http://jsfiddle.net/Bonomi/KgndE/ This is the HTML: <div class="row"> <div class="la ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

Passing variables to the ajax.done() function from within a loop - what you need to know

How can I pass a variable to the .done() method of an ajax call that is inside a loop? The code snippet below shows my initial attempt: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </ ...

Using React.js to create table cells with varying background colors

For my React application, I am working with a table that utilizes semantic ui. My goal is to modify the bgcolor based on a condition. In most cases, examples demonstrate something like bgcolor={(condition)?'red':'blue'}. However, I requ ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

Create a variety of elements in real-time

My goal is to utilize JavaScript in order to generate a specific number of input boxes based on the user's input. However, I encountered an issue where using a for loop only creates one input box and then appends this same input box multiple times. f ...

Tips for narrowing down table searches to only rows containing certain text within a column

Currently, I have a function that allows me to search through my table: //search field for table $("#search_field").keyup(function() { var value = this.value; $("#menu_table").find("tr").each(function(index) { if (index === 0) return; var id = $( ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

Experience the click action that comes equipped with two unique functions: the ability to effortlessly add or remove a class

Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement. Upon clicking on a link: Add a class of "current" Remove the class of "current" from ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

Is it permissible to assign the same element as a child to multiple parent elements in jQuery?

Imagine you have the following HTML structure: <div id="first"></div> <div id="second"></div> Now, if you use JavaScript and JQuery to perform the following actions: var $child = $("<span id='child'>Hello</span ...

Trouble with CSS transitions not functioning while altering React state

Each time a user clicks on an accordion, the content should smoothly show or hide with a transition effect. However, the transition only seems to work when opening a closed accordion, not when closing an already open one! To get a clearer idea of this iss ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

Clicking on a link in HTML with the onclick event

I am looking to create a button that will direct me to a different page. Here is the code snippet I have: <div align="right" ><input type="submit" id="logout" onclick="location.href='/login?dis=yes'" value="Sign Out" ></div>& ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

Retrieve all chosen option elements from every select element within a form

Hello everyone and thank you for offering your assistance in answering my query. I am currently working on a form that includes 6 select elements all having the "skillLevel" class. I am looking to extract the values of each select element, preferably in a ...