0

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)');
}
1
  • 6
    $('#intro').css("background-image", 'url('+apiImg+')'); Commented Feb 16, 2017 at 19:23

1 Answer 1

2

Use strings concatenation:

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

or ES6 template literals:

$('#intro').css("background-image", `url(${apiImg})`);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answers! I used (' + apiImg + ') and it worked.

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.