cmegown
cmegown

Reputation: 411

Dynamic image alignment with Javascript

I've got a Javascript curiosity that I must satisfy. Before I begin I should let you know that I am very aware of the fact that this can be handled with CSS alone, but I want to improve my Javascript skills so humor me :)

For reference to what I'm trying to get at: http://codepen.io/cmegown/pen/CGhpa

Let say we have a potentially infinite number of images, each wrapped inside of a figure set to display: inline-block so that it is the same size as the image inside. Each of these images can be any dimension, and the desired result is that the bottom of every image is perfectly aligned. The kicker here is that this is responsive, so the images may scale up or down. Here's my thinking of how this might be accomplished:

Loop through every image and find the tallest one (outerHeight), then grab that same image's width (outerWidth). Subtract the outerWidth from the outerHeight to get the "master" difference. Loop again through each image to calculate the difference for each specific image and subtract that from the "master" difference, then apply that number to the top margin. Rinse and repeat until each image is aligned to the bottom of the tallest image.

Right? I think the logic is sound, I just lack the skills to put this together properly in Javascript. Sorry for the super long post, but any and all help/advice is appreciated!

Upvotes: 0

Views: 171

Answers (1)

Aguardientico
Aguardientico

Reputation: 7779

function alignImages() {

  // caching selectors
  var imgs = document.getElementsByTagName('img'),
      maxHeight = 0;
  for (idx in imgs) {
    var img = imgs[idx];
    if (img.height > maxHeight) {
      maxHeight = img.height;
    }
  }
  for (idx in imgs) {
    var img = imgs[idx];
    img.style.marginTop = (maxHeight - img.height) + "px";
  }


}

Upvotes: 1

Related Questions