Appending images to a div of custom height and width with Javascript only works with set dimensions

- 1 answer

Ad

I am trying to pull the front page of Reddit using a HTTP GET request and then display a web page that consists of just the images from the thumbnail.

Here is the code so far I have that succesfully gets the image's URL and image dimensions. After I get the information I need for each one I am trying to create a new div element and append it to the gridArticle element I get by ID. Before doing so I am updating its class name as well as image and size.

 $.getJSON("https://www.reddit.com/.json", function (data) {
    var items = [];
    $.each(data.data.children, function (i, obj) {
        if ((obj.data.preview != null) && (obj.data.preview.images != null)) {

            var imageSourceUrl = preview.images[0].source.url;
            var height = preview.images[0].source.height;
            var width = preview.images[0].source.width;

           var listingEntry = document.createElement("div");
            listingEntry.className = "tile";
            listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")";
            listingEntry.style.width = width
            listingEntry.style.height = height;



            var gridArticle = document.getElementById("gridArticle");
            gridArticle.appendChild(listingEntry);

        }
    });
});

HTML

<article id="gridArticle">


  </article>

CSS

   article .tile {

    display: block;
    float: left;
    box-sizing: border-box;

    font-size: 3em;
    font-weight: 700;

    padding: 0 6px;
    color: #fff;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;

    border:1px dotted black;
  }

However if I remove the background-size property and in the parent article .tile{} add the height and width property's there and set them to a fixed length (100 px 100 px for example) the images show up fine but just at the specified dimensions.

Any ideas?

Ad

Answer

Ad

You're adding the images to the divs you're inserting as backgrounds. As such they're behaving entirely as you would expect - if a div has no content then it won't occupy any space therefore you aren't going to see any background. Setting a background size won't affect the dimensions of the div itself.

Solutions:

  1. Take your existing height and width variables in JS and apply them as CSS height and width. You won't need to bother setting a background size; in CSS make the size 'cover'.
  2. Use real image elements instead of backgrounds on a div.
Ad
source: stackoverflow.com
Ad