I have been working on this code where I need to take input from the user via HTML buttons and then assign that input URL of an image from the web to the .bg {background: URL('URL') } in my CSS file. Is there some way I can do that?
.bg {
background: URL(' *user input image URL * ')
}
CodePudding user response:
So as you see here I am updating the background after 3 seconds. This will not change the css file but will change the css in real time. All you need to do is update what is stored in the background style portion of the element. You just need the link to the image. If you want to update permanently in the css there are 2 ways to go about it, keeping the css the same and changing the reference file or writing to the css file with a different script and reloading.
setTimeout(function () {
document.getElementById("bg").style.background ="URL('https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI')";
}, 3000);
#bg {
color: blue;
background: URL('https://i.picsum.photos/id/237/200/300.jpg?hmac=TmmQSbShHz9CdQm0NkEjx1Dyh_Y984R9LpNrpvH2D_U');
height: 400px;
}
<div id="bg"></div>
CodePudding user response:
I think you can do like this
function setImage() {
const input_from_user = document.getElementById("input_from_user");
const image_url = input_from_user.value;
const bg_container = document.getElementsByClassName("bg")[0];
bg_container.style.backgroundImage = `url(${image_url})`;
}
.bg {
width: 400px;
height: 200px;
background-repeat: no-repeat;
background-size: contain;
background-position: center center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div ></div>
<input type="text" id="input_from_user" />
<button onclick="setImage()">Set Image</button>
</body>
</html>
Can try with this image: https://www.google.nl/images/srpr/logo3w.png
Hope this can help.