gogosimba
gogosimba

Reputation: 55

Including a variable into an url string in javascript

I'm wondering how to insert the imageId number into the url string, I got confused when there's a string inside a string.

const imageId = 13935764;

switchBackground.onclick = function(){
  setbg.style.backgroundImage = "url('https://images.pexels.com/photos/'+imageId+'pexels-photo-13366951.jpeg?cs=srgb&dl=pexels-kwnos-iv-13366951.jpg&fm=jpg')";
}

Upvotes: 0

Views: 37

Answers (1)

user2182349
user2182349

Reputation: 9782

You can use template literals (backticks)

switchBackground.onclick = function(){
  setbg.style.backgroundImage = `url('https://images.pexels.com/photos/${imageId}pexels-photo-13366951.jpeg?cs=srgb&dl=pexels-kwnos-iv-13366951.jpg&fm=jpg')`;
}

The issue is that the double-quotes is treating the entire string as a literal and not adding in the imageId.

Upvotes: 2

Related Questions