0

so I have an array, containing titles and covers for movies. I'm trying to display the names in the flexbox, using cover image as background image. I also tried to write it like that: document.div.style.backgroundColor = "url(infoForThatDay[each]['cover'])"; but it didn't work either

Here is the snippet of my code:

for(let each in moviesToDisplay) {
    let div = document.createElement("div")
    div.innerText = moviesToDisplay[each]['title'];
    
    //That is where I'm trying to set the background color
    div.style.backgroundColor = "url(moviesToDisplay[each]['cover'])";
    flex.appendChild(div);
}

Thank you in advance <3 have a great day ^_^

3
  • Remove the quotes around "url(infoForThatDay[each]['cover'])" so that the expression is evaluated and not used literally as the background color. Commented Jun 22, 2022 at 16:01
  • This is incorrect @ScottMarcus, you still need url() if it's an image value. Commented Jun 22, 2022 at 16:06
  • @bryce Yes, but you don't want quotes around the dynamic portion. Commented Jun 22, 2022 at 16:08

2 Answers 2

1

You need to use string interpolation to get the value. You also can't use url values with background-color, you should use background instead:

div.style.background = `url(${moviesToDisplay[each]['cover']})`;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much, i figured i needed to use ``-s but i couldn't figure out where <3
0
div.style.background = `url("${moviesToDisplay[each]['cover']}")`;

To set image as background, either set backgroundImage or background property.

Also, you will need to use string interpolation else it will set the background image to whatever the string is.

Also, url() takes a string, that's why "" are required.

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.