Home > Enterprise >  How to use variable as background image from textbox?
How to use variable as background image from textbox?

Time:11-21

at the moment I am struggling to figure out this problem. I am attempting to make a textbox set the background of the website. Here is my code:

<!DOCTYPE html>
<html>
<body>

Enter URL: <input type="text" id="myText">

<button onclick="myFunction()">Set Wallpaper</button>
<script>
function myFunction() {
  var x = document.getElementById("myText").value;
  document.body.style.background = x;
}
</script>

</body>
</html>

CodePudding user response:

CSS background property only accepts values in some defined format.

You can use some predefined colors i.e. green or red

document.body.style.background = 'green';

or use some image

let img_url = 'path_to.jpg';
document.body.style.background = `url(${img_url})`;

See https://developer.mozilla.org/en-US/docs/Web/CSS/background for more info

CodePudding user response:

Well, u cannot simply set your background as text, that's weird. If u want to set it from url and have the image on the bg, then try something like this:

function myFunction() {
  var x = document.getElementById("myText").value;
  document.body.style = 'background-image: url(${x});';
}

  • Related