I successfully implemented a random background script that assigns a unique bgimage to each page.
<script type="text/javascript">
function assignBackground() {
let randomInt = Math.floor(Math.random() * 160);
document.body.style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
document.body.style.backgroundRepeat = "repeat";
document.body.style.backgroundPosition = "absolute";
document.body.style.backgroundSize = "cover";
}
</script>
<script type="text/javascript">
assignBackground();
</script>
Now, I am facing an issue where I need to apply the background image to a DIV element with a specific class. The desired result is:
<div class="MySpecialDiv" style="background-image: url(../../main_img/slider/image1.jpg);"></div>
I have tried using both document.getElementsByClassName and document.getElementById methods without success.
Any suggestions?
In response to this challenge, I attempted...
<script type="text/javascript">
function assignBackground() {
let randomInt = Math.floor(Math.random() * 160);
document.getElementById("heroBg").style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
document.body.style.backgroundRepeat = "repeat";
document.body.style.backgroundPosition = "absolute";
document.body.style.backgroundSize = "cover";
}
</script>
<div class="MySpecialDiv"></div>
<body>
<script type="text/javascript">
assignBackground();
</script>
as well as
<script type="text/javascript">
function assignBackground() {
let randomInt = Math.floor(Math.random() * 160);
document.getElementsByClassName("MySpecialDiv")[0].style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
document.body.style.backgroundRepeat = "repeat";
document.body.style.backgroundPosition = "absolute";
document.body.style.backgroundSize = "cover";
}
</script>
<body>
<script type="text/javascript">
assignBackground();
</script>
Unfortunately, the function does not execute when inspecting the HTML. It seems like the script is not running properly.