Skip to content

Instantly share code, notes, and snippets.

@FuruholmAnton
Created November 11, 2015 05:49
Show Gist options
  • Save FuruholmAnton/423b718c94a8e8d7820d to your computer and use it in GitHub Desktop.
Save FuruholmAnton/423b718c94a8e8d7820d to your computer and use it in GitHub Desktop.
var gallery = {
container: null,
containerPadding:0,
containerWidth:0,
itemsArray:[],
itemMargin:0,
items:[], // Array of all the <img>
count:[],
maxWidth:0,
initImages:function(){
this.containerPadding = getValue(QS(".gallery"),'padding-left') * 2;
this.containerWidth = getValue(QS(".gallery"), 'width');
this.itemMargin = getValue(QS(".gallery-item"), 'margin-left') * 2;
this.items = QSA(".gallery-item");
this.container = QS(".gallery"); // Container of the images
for (var i = 0; i < this.items.length; i++) {
this.itemsArray.push(i);
this.items[i].style.height = '';
this.items[i].style.width = '';
};
this.setImages();
},
setImages:function(){
this.maxWidth = 0;
this.count = [];
var img;
for (var i = 0; i < this.itemsArray.length; i++) {
if(this.maxWidth < (this.containerWidth - this.containerPadding * 2 - this.itemMargin*2)){
img = getValue(this.items[this.itemsArray[i]], 'width');
this.maxWidth += img;
this.count.push(i);
}
// log(items[i].offsetWidth);
};
if(this.itemsArray.length > 0){
this.fixImages();
}
},
fixImages:function(){
var diffWidth = 0; // init diff
var diffHeight = 0; // init diff
var img;
var imageWidth;
var imageHeight;
var firstImg;
if(this.count.length === 1 && this.itemsArray.length === 1 && window.innerWidth > 900){
this.itemsArray.shift();
}else{
for (var i = 0; i < this.count.length; i++) {
// calculates the new width
firstImg = this.items[this.itemsArray[0]];
imageWidth = getValue(firstImg, 'width');
//get porpotions
var prop = firstImg.naturalHeight / firstImg.naturalWidth;
imageHeight = imageWidth * prop;
diffWidth = imageWidth * (this.containerWidth / this.maxWidth);
diffHeight = imageHeight * (this.containerWidth / this.maxWidth);
firstImg.style.width = diffWidth - (this.containerPadding / this.count.length) - this.itemMargin + 'px';
firstImg.style.height = diffHeight - this.itemMargin + 'px';
this.itemsArray.shift();
};
};
if(this.itemsArray.length > 0){
this.setImages();
}else{
log("finished");
ID("loadingMessage").style.display = "none";
var allImages = QSA(".gallery-item");
for (var i = 0; i < allImages.length; i++) {
allImages[i].style.opacity = "1";
};
}
}
}; // end of gallery object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment