I'm trying to find a way to detect the orientation of images (landscape or portrait).
The HTML simply contains a few img tags with source already filled in. The script should then detect the orientation and add the images to dynamically created divs acting as thumbnails.
The script I've been using is this (found it on here somewhere)
for (i = 0; i < pics.length; i++) {
pics[i].addEventListener("load", function() {
if (this.naturalHeight > this.naturalWidth) {
this.classList.add("portrait")
} else {
this.classList.add("landscape")
}
})
}
Now this usually works fine when first loading the page. When refreshing however, it behaves erratically, adding the right class to some images and not adding any class at all to others.
I also tried this
for (i = 0; i < pics.length; i++) {
var img = pics[i];
var width = img.naturalWidth;
var height = img.naturalHeight;
if (height > width) {
img.classList.add("portrait")
} else {
img.classList.add("landscape")
}
}
Which also works unpredictably. All images get a class added to them, but some get the wrong one.
I'm guessing the problems might come from the images not completely loading before the script runs and thus the script not being able to measure them correctly, but I'm not sure. Anyhow, I don't really know how to fix it either.
To give an idea of what I'm going for, here's a link to the page: http://pieterwouters.tumblr.com/
Any ideas much appreciated.