JavaScript Image Grid Different Sizes and Width

JavaScript Image Grid Different Sizes and Width
Code Snippet:500px Gallery Layout
Author: no
Published: January 17, 2024
Last Updated: January 22, 2024
Downloads: 7,421
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create image grid with different sizes and width. It arrange images in a responsive masonry grid layout that automatically adjust their sizes according to device width. You can use this code in your gallery/showcase projects.

The code snippet generates image gallery dynamically using template system.

How to Create JavaScript Image Grid with Different Sizes and Width

1. First of all, create the HTML structure as follows:

 <div id="gallery"></div>

<script type="text/tmpl" id="tmpl">
<% for (let i = 0; i < imgs.length; i++) { %>
	<div class="img" style="width:<%=imgs[i].ww%>px;height:<%=imgs[i].hh%>px">
  	<img src="<%=imgs[i].src%>"/>
  </div>
<% } %>
</script>

2. After that, add the following CSS styles into your project:

body {
  margin: 0;
}
#gallery {
	position: relative;
	padding: 5px;
}
.img {
  display: block;
  margin: 5px;
  float: left;
  background: #ececec;
}
.img img {
  width: 100%;
  height: 100%;
}

3. Finally, add the following JavaScript code and done.

(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

function randomImg () {
  let count = 10 + Math.ceil(Math.random() * 10)
  let imgs = []
  for (let i = count; i > 0; i--) {
    let w = 250 + 10 * Math.ceil(Math.random() * 50)
    let h = 200 + 10 * Math.ceil(Math.random() * 50)
    imgs.push({
      src: 'https://unsplash.it/' + w + '/' + h,
      w: w,
      h: h
    })
  }
  return imgs
}
function countImgsInCol (idx, imgs) {
  let gallery = document.querySelector('#gallery')
  let gw = gallery.clientWidth
  let maxEachCol = 4
  let minH = 120
  let count = 0
  for (let i = Math.min(maxEachCol, imgs.length - idx); i > 0; i--) {
    let w = 0
    for (let j = idx; j < idx + i; j++) {
      let minW = minH * imgs[j].w / imgs[j].h
      if (minW >= gw) {
        return 1
      } else {
	      w += minW
      }
    }
    if (w < gw) {
      count = i
      break
    }
  }
  return count
}
function getCols (imgs) {
  let cols = []
  let rest = imgs.length
  let count = 1;
  for (let i = 0; i < imgs.length; i = i + count) {
    count = countImgsInCol(i, imgs)
    console.log(i, count)
    cols.push({start: i, end: i + count - 1, total: count})
  }
  return cols
}
function organizeImg (imgs) {
  let gallery = document.querySelector('#gallery')
  let galleryW = gallery.clientWidth
  let margin = 10
  let cols = getCols(imgs)
  for (let i = 0; i < cols.length; i++) {
    let col = cols[i]
    let colH = 0
    let scale = 0
    for (let j = col.start; j <= col.end; j++) {
      scale += imgs[j].w / imgs[j].h
    }
    colH = (galleryW - margin * (col.total + 1)) / scale
    console.log(colH)
    for (let k = col.start; k <= col.end; k++) {
      let img = imgs[k]
      img.hh = colH
      img.ww = colH * img.w / img.h
     }
  }
  gallery.innerHTML = tmpl('tmpl', { imgs })
}
let imgs = randomImg()
organizeImg(imgs)
window.addEventListener('resize', () => {
  organizeImg(imgs)
})

That’s all! hopefully, you have successfully integrated this image grid code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...