Retrieve the initial offsetHeight
of all img
elements that you wish to maintain a constant height for, and then set their height
property to this obtained value.
The specific line responsible for this operation in the code snippet below is:
img.style.height = img.offsetHeight + "px";
let gallery = [
'https://picsum.photos/200/100/?image=1080',
'https://picsum.photos/200/200/?image=1063',
'https://picsum.photos/500/200/?image=1060',
'https://picsum.photos/300/300/?image=1059',
'https://picsum.photos/200/300/?image=1070',
'https://picsum.photos/300/200/?image=1071'
];
let thumbs = document.getElementById("thumbnails");
for (let i = 1; i < gallery.length; i++) {
thumbs.appendChild(thumbs.firstElementChild.cloneNode(true));
}
let img = document.querySelector(".col-md-7").firstElementChild;
gallery.forEach((url, i) => {
thumbs.children[i].firstChild.src = url;
});
thumbs.addEventListener("click", event => {
if (event.target.tagName === "IMG") {
img.src = event.target.src;
}
});
img.src = gallery[0];
img.style.height = img.offsetHeight + "px";
// The above last line is the code maintaining the initial height.
#thumbnails {
list-style-type: none;
padding: 0;
}
#thumbnails li {
float: left;
height: 35px;
width: 50px;
margin: 10px;
background: #fde;
}
#thumbnails img {
width: 100%;
height: 100%;
}
<div class='col-md-7'>
<img>
</div>
<div class='col-md-5'>
<ul id="thumbnails">
<li><img></li>
</ul>
</div>
EDIT: (responding to a comment)
Based on my current understanding, an approach like the following can be taken:
HTML
Each gallery now has been encapsulated within a
<div class="gallery"></div>
. Thumbnail image sources are dynamically added using
ng-repeat
.
<div class="gallery">
<div class='col-md-7'>
<img src='something'>
</div>
<div class='col-md-5'>
<ul class="thumbnails">
<li ng-repeat="some-token">
<img src="{{img.src}}">
<!-- img.src represents the URL from each iteration in your data -->
</li>
</ul>
</div>
</div>
<div class="gallery">
<div class='col-md-7'>
<img src='something'>
</div>
<div class='col-md-5'>
<ul class="thumbnails">
<li ng-repeat="some-token">
<img src="{{img.src}}">
</li>
</ul>
</div>
</div>
JS
This script iterates through each gallery in the galleries
collection, ensuring that each gallery maintains its own scope.
let galleries = document.getElementsByClassName("gallery");
[].forEach.call(galleries, gallery => {
let image = gallery.querySelector("img");
image.style.height = image.offsetHeight + "px"; // Initial height
let thumbs = gallery.querySelector(".thumbnails");
thumbs.addEventListener("click", event => {
if (event.target.tagName === "IMG") {
image.src = event.target.src;
}
});
});