Search code examples
javascripthtmlvariables

Using script Variables as a Background Image Source in HTML


I'm trying to use a script variable as a background image source for a body element in HTML, but no solution on the internet has worked.

<script>
    #Some conditions and variables that form the final variable
    var backimage = 'images/' + image + '.jpg'
  </script>
<style>
      body {
        background: url(#backimage varable here) no-repeat center center fixed;
        background-size: cover;
        ...

I tried using code like this

Script:

    window.onload = function() {
      document.getElementById('paragraph').style.background = 'url('+iimage+')';

HTML:

        background: <p id="paragraph"></p> no-repeat center center fixed;

But this does not give any results.

How i can use backimage variable correctly?


Solution

  • from your code, i will believe image is a variable set somewhere, I used a free image link as image for example, all you need to do is include your own link and asset the background-image with JavaScriot

        var image = "https://images.unsplash.com/photo-1713528199169-9488eb2d2b79?q=80&w=2787&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"; // Assuming 'image' is defined elsewhere
     var backimage = image;
     document.addEventListener("DOMContentLoaded", function() {
    // Set the background image of the body element
    document.body.style.background = `url(${backimage}) no-repeat center center fixed`;
     });