skip to Main Content

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?

3

Answers


  1. 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`;
     });
    Login or Signup to reply.
  2. 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`;
     });
    Login or Signup to reply.
  3. It could be because you didn’t set a size for the

    tag
    Try to do it like this:

       <p id="paragraph" style="width:150px;height: 150px;">no-repeat center center fixed;</p> 
    

    In the script instead of "background" write "backgroundImage"
    And pay attention to set the image as it is important to you that they see it, if you want for example to see the whole image set in the script in addition:

            style.backgroundSize= "contain";
    

    If something is not clear enough, ask.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search