I've been exploring a way to dynamically update the background image of an HTML document using JavaScript. While I am familiar with hardcoding the links, I'm interested in loading it from a variable URL that I specify. Here is what currently works:
<!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>
However, this is what I actually 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>
Does anyone have any suggestions on how to achieve this?