-1

I feel like this might be a stupid question. I am trying to make the background image of a div change based on whatever object is selected.

`

previewBackground.style.backgroundImage = "url(`/images/object.firstName}.png`)";

`

I need to escape the doubles quotes for the URL to fill in the object.firstName property. Can someone help me with the syntax here?

I have tried using single quotes of the URL, as well as . Single quotes don't do the trick, and turn my entire escape my entire URL.

I have also tried a \ but this only affects the following character and feel like there has to be a more efficient way to do this.

Thanks! I am pretty new to JS.

Liam
  • 1
  • 2

1 Answers1

3

You will want to use the ticks to start and end the entire string. Then include double quotes within the URL and don't forget when using template literals, to start with the dollar sign $

let previewBackground = document.querySelector("#previewBackground");
let object=  {
  firstName: "350x150"
};

previewBackground.style.backgroundImage = `url("https://via.placeholder.com/${object.firstName}")`;
#previewBackground{
width:350px;
height:150px;
border:1px solid #000;
}
<div id="previewBackground"></div>
imvain2
  • 15,480
  • 1
  • 16
  • 21
  • This solution is elegant and supported by most modern web browsers: 96.97% according to [caniuse.com](https://caniuse.com/template-literals). It compatibility with older browsers is needed, simply concatenate the elements with the `+` operator: `'url("https://via.placeholder.com/' + object.firstName + '")'` – Mehdi Nov 01 '22 at 19:57
  • Thank you! Works as expected. – Liam Nov 01 '22 at 20:29
  • Also see: [Is quoting the value of url() really necessary?](https://stackoverflow.com/questions/2168855/is-quoting-the-value-of-url-really-necessary) – Yogi Nov 01 '22 at 21:01