0
document.body.style.backgroundImage = "url('images[0]')";

I want to set the backgroundImage of the CSS body element as the image i have stored in image[0], however whenever I try to do so I get an error in the javascript console saying net::ERR_FILE_NOT_FOUND.

I assume this is because it is looking for an image called 'images[0]' which doesn't exist and so I get an error. How can I set it so that it reads the image that is actually stored in images[0]?

Sorry if this has been asked before, I couldn't find any other questions like it when I looked.

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
Shane Byrne
  • 3
  • 1
  • 1
  • 2

4 Answers4

2

Have a look at this simple lines:

I'm pretty sure you are missing the " quotes. So you can combine your variable and the "url()" using the Plus character (+) to get something like this: "url('"+images[0]+"')"


let images = ["https://pbs.twimg.com/profile_images/643819371656294405/F-pVCbHg_400x400.png"]

document.body.style.backgroundImage = "url('"+images[0]+"')";

Or another way could be to use a way modern technique using this line (See the docs):

let images = ["https://pbs.twimg.com/profile_images/643819371656294405/F-pVCbHg_400x400.png"]

document.body.style.backgroundImage = `url('${images[0]}')`;
0

Try document.body.style.backgroundImage = "url(" + images[0] + ")"; instead.

With ES2015 you can also achieve it with backticks `
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

0

Modern JS has template literal syntax that gives string interpolation capabilities.

document.body.style.backgroundImage = `url('${images[0]}')`;

As you can see, the template literal is delimited with a pair of outer backticks instead of the typical single or double quotes.

The interpolation in a template literal happens by enclosing the expression that should be evaluated within the ${} delimiter. The result of the expression becomes the injected value.

0

With modern JavaScript it's achieved with template literals.

So you can do the following:

document.body.style.backgroundImage = `url('${images[0]}')`;
neuro_sys
  • 805
  • 7
  • 13