Search code examples
javascripthtmlcssbackground-imagegetjson

Set background-image of <div> in JavaScript


I am trying to set the background-image property of a <div> in Javascript, but the image won't appear. The height is 100px, and I can see that the content beneath it is pushed down, but here is no image.

Here is my code:

var bg = document.createElement("div");

$.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function(data) {
    bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg");';
    bg.style.height = "100px";
    statsDiv.appendChild(bg);
    //some other stuff that uses the JSON that doesn't matter
});

I know that the <div> is there, because It shows the 100px gap in between the elements, but no image, and the $.getJSON() works.

Solution:

I just had to remove the semicolon:

Before: bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg");';

After: bg.style.backgroundImage = 'url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg")';


Solution

  • Looks good so far. The new div has to be appended to the DOM.

    $.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function() {
        console.log("success");
    
        var bg = document.createElement("div");
        document.body.appendChild(bg);
        bg.style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg')";
    
        bg.style.height = "100px";
    
      })
      .done(function() {
        console.log("second success");
      })
      .fail(function() {
        console.log("error");
      })
      .always(function() {
        console.log("complete");
      });
    div {
      border: 1px solid red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>