0

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!

1
  • 1
    Use a template string. `url('${myObj.imageURL}')`; Commented Feb 14, 2018 at 21:39

3 Answers 3

2

Very close, you were ;)

newbox.style.backgroundImage = "url("+myObj.imageURL+")";
Sign up to request clarification or add additional context in comments.

1 Comment

Wow that was quick! Thanks a lot this works just fine! Awesome :D
0

I think your string is wrong. Use this:

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

Comments

0

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>

Comments

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.