Tarantulino
Tarantulino

Reputation: 1

How to use a variable as a filepath in JS?

While trying to build some dynamic content for a webpage, I encountered a strange problem. I did some research but I could not find anything that would help me...

Here is my code where I try to change the background image of a div. The file path for the background image is stored in an object which is received as JSON and parsed to a javascript object. When I fill the innerHTML of the div with the content of the filepath variable, the correct URL is displayed. And when I write this exact URL into the backgroundImage URL, the correct picture is displayed. However when I try to replace the file path with the variable, nothing happens.

    var myObj = JSON.parse(this.responseText);
            var URL = JSON.stringify(myObj.imageURL);
            newbox.style.backgroundImage = "url('myObj.imageURL')";
            newbox.innerHTML += myObj.Content;
            newbox.innerHTML += myObj.imageURL;
            insert.append(newbox);

In my code you can see that I also tried to stringify the value of myObj.imageURL and use this as the file path. But this did not work either.

EDIT: the filepath stored in myObj.imagURL looks like this: images/crew.jpg

EDIT 2: The problem has been solved by Manuel Otto:

    newbox.style.backgroundImage = "url("+myObj.imageURL+")";

Thanks for all the advise!

Upvotes: 0

Views: 2737

Answers (3)

Subash
Subash

Reputation: 7266

This is a fully working code.

var myObj = {
	imageURL: "https://images.unsplash.com/photo-1494249465471-5655b7878482?ixlib=rb-0.3.5&s=997116405ede44d63ddc54f16e2db8ce&auto=format&fit=crop&w=1350&q=80",
  Content: "my div content"
}

var URL = JSON.stringify(myObj.imageURL);

var insert = document.getElementById("insert");
var newbox = document.createElement("DIV");


newbox.style.backgroundImage = `url('${myObj.imageURL}')`;
newbox.style.height = "400px";
newbox.innerHTML += myObj.Content;
newbox.innerHTML += myObj.imageURL;
insert.append(newbox);
<div id="insert"></div>

Upvotes: 0

wOOdy...
wOOdy...

Reputation: 669

I think your string is wrong. Use this:

newbox.style.backgroundImage = "url('" + myObj.imageURL + "')";

Upvotes: 0

Manuel Otto
Manuel Otto

Reputation: 6540

Very close, you were ;)

newbox.style.backgroundImage = "url("+myObj.imageURL+")";

Upvotes: 2

Related Questions