Appending an image that fits set dimensions using javascript

- 1 answer

Ad

I am trying to append images to a element with a specified height and width. The image itself may be bigger or smaller than that height and width and I want to adjust the image to fit the size rather than repeating or showing only part of the image.

Javascript:

I got the URL of the image as well as its height and width, then I tried creating the element and setting its properties here.

     var listingEntry = document.createElement("img");
     listingEntry.setAttribute("height", height);
     listingEntry.setAttribute("width", width);
     listingEntry.className = "classTitle";
     listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")";

Then I got the element from the DOM by Id and appended it:

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

And my CSS:

article .tile {

display: inline-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;

}

article img {

}

I tried:

article img {
   max-height: 100% 
   max-width: 100%
}

But then the images stopped showing up all together.

Ad

Answer

Ad

I would approach this in two different ways:

1) Create a div and set a background image:

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

or 2) Create an img and set a src that points to the url:

var listingEntry = document.createElement("img");
listingEntry.setAttribute("height", height);
listingEntry.setAttribute("width", width);
listingEntry.className = "classTitle";
listingEntry.src = imageSourceUrl;

NOTE: I would go with the second approach. Also try to avoid setting a background image to an img element, since the element's content tend to mask the background.

Ad
source: stackoverflow.com
Ad