0

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')";
}

2
  • 3
    You'll need to fix your quotes: "url('…"+imageId+"…')" Commented Oct 24, 2022 at 0:43
  • 1
    Better yet, use a template string `url('https://images.pexels.com/photos/${imageId}pexels-photo-13366951.jpeg?cs=srgb&dl=pexels-kwnos-iv-13366951.jpg&fm=jpg')` Commented Oct 24, 2022 at 0:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.