0

I have a variable in which I populate the image location dynamically.

I need to change the background image with that variable. I am not able to find a way to do that.

var myImg = '/images/example1.jpg';

document.body.style.background = "url(myImg) no-repeat"; 

This doesn't seem to work.

Is there a syntax issue or should this be done in a different way?

2 Answers 2

1

myImg is the literal word in side the string. Use concatenation to use the variable:

document.body.style.background = "url(" + myImg + ") no-repeat";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the answer. I am just learning. Really appreciate the quick help..
0

I like this way

var bodyStyle = document.body.style;

bodyStyle.backgroundImage = 'url(' + yourImage + ')';

bodyStyle.backgroundRepeat = 'no-repeat'

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.