Bribenn
Bribenn

Reputation: 5

Use a variable in jquery .css()?

I'm trying to use an api call to change the background of a div based on the current weather. The url is not working in the last line. If I add a path from a file in my folders it works, but not when I try to add a variable as the url path. Is there a workaround to use a variable in the url path? Here's what I have:

function loadImage(conditions){
    var imageSRC = "img/weather/hero-";
    var validConditions = ["clear", "cloudy", "rain", "snow"];
    var timeOfDay = getTimeOfDay();
    conditions = conditions.toLowerCase();
    if (validConditions.indexOf(conditions) === -1) {
        conditions = "cloudy";
    } else {
        conditions = conditions;
    }
    console.log(conditions);

    var apiImg = imageSRC + conditions + ".jpeg";
    console.log(apiImg);

    $('#intro').css("background-image", 'url(apiImg)');
}

Upvotes: 0

Views: 52

Answers (1)

Antonio
Antonio

Reputation: 901

Use strings concatenation:

$('#intro').css("background-image", 'url(' + apiImg + ')');

or ES6 template literals:

$('#intro').css("background-image", `url(${apiImg})`);

Upvotes: 2

Related Questions