user10980551
user10980551

Reputation:

How to change BgImage dynamically using JS

I was looking for a way to dynamically change the BgImage of an HTML document with JS. I know about hardcoding the links, but I want to load it from a variable url that I provide. This is what's working

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url('https://i.imgur.com/B95LprK.jpg')";
}
</script>

</body>
</html>

But this is what I need

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
var imageLink = 'https://i.imgur.com/B95LprK.jpg'
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url(imageLink)";
}
</script>

</body>
</html>

Any idea on how to achieve this?

Upvotes: 0

Views: 38

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

The easiest way is to use a template literal string with backticks ` ` in which you can inject variables.

var imageLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = `url(${imageLink})`;

An older way of doing it is by concatenating strings with the + operator.

var imageLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = "url(" + imageLink + ")";

Upvotes: 1

Related Questions