Ringrong Ringrong - 3 months ago 11
HTML Question

Display images from array in HTML

I need create a load-on-demand image gallery, and I start from a JSON that defines all the images in the gallery in a format like:

var GALLERY_JSON = {
"size" : "200x200",
"images": [
{
"src" : "http://aws.netclime.net/Images/1.png",
"text" : "This is an image1",
"link" : "http://cnn.com"
},
{
"src" : "http://aws.netclime.net/Images/2.png",
"text" : "This is an image2",
"link" : "http://google.com"
},
…,
{
"src" : "http://aws.netclime.net/Images/3.png",
"text" : "This is an imageN",
"link" : "http://yahoo.com"
}
]
};


I tried this:

function getArticleImage() {
var image = new Image;
image.className = 'banner-img';
image.src = 'aws.netclime.net/Images/1.png';
image.setAttribute("height", "200px");
image.setAttribute("width", "200px");
image.onload = function() {
image.classList.remove();
};
return image;
}


I need an advice, which is the proper way to display those images with text and link in HTML?

Answer

This should get you started...

var GALLERY_JSON = {
   "size" : "200x200",
   "images": [ 
      {
         "src" : "http://aws.netclime.net/Images/1.png",
         "text" : "This is an image1",
         "link" : "http://cnn.com"
      },
      {
         "src" : "http://aws.netclime.net/Images/2.png",
         "text" : "This is an image2",
         "link" : "http://google.com"            
      },
      {
         "src" : "http://aws.netclime.net/Images/3.png",
         "text" : "This is an imageN",
         "link" : "http://yahoo.com"            
      }
   ]
};

function getArticleImage(data) {
    var image = new Image;
    image.className = 'banner-img';
    image.src = data.src;
    image.setAttribute("height", data.size);
    image.setAttribute("width", data.size);
    image.onload = function() {
      image.classList.remove();
    };
    return image;
}

GALLERY_JSON.images.forEach(function(data){
  data.size = "200px"; // you should get this from `GALLERY_JSON.size`
  document.body.appendChild( getArticleImage(data) );
})