hello friends i am trying to get the size (height and width) of an image from an hrf and put these values in its attribute
This is driving me crazy
this is my html:
<figure>
<a href="image-large-1.jpg">
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg">
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg">
<img src="image-small-3.jpg"/>
</a>
</figure>
this is what I want :
<figure>
<a href="image-large-1.jpg" original-size="1000x800"> //the sizes are example
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg" original-size="1200x700"> //the sizes are example
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg" original-size="900x980"> //the sizes are example
<img src="image-small-3.jpg"/>
</a>
</figure>
the "original-size" attribute I want to get it from " a hrf "
I was trying with this code that I found here, I get the original size of the image-large from the href (in the console.log) but I cannot print them in the html
help me please
$(".containerGallery figure a").each(function() {
var imgSrc, imgW, imgH;
function myFunction(image){
var img = new Image();
img.src = image;
img.onload = function() {
return {
src:image,
width:this.width,
height:this.height};
}
return img;
}
var x = myFunction($(this).attr('href'));
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
$(this).each(function() {
x.addEventListener('load',function(){
console.log(imgW+'x'+imgH);
$(this).attr('original-size', imgW+'x'+imgH);
});
});
});
The JavaScript code in the question is overly complex and redundant.
Here's some simplified code that accomplishes the same thing.
// get all <a> elements inside <figure> elements
const atags = Array.from(document.querySelectorAll('figure a'));
// iterate over every <a> tag
atags.forEach(atag => {
// create blank image element
var img = new Image();
// when the image loads, store its dimensions to the atag's
// `data-original-size` attribute
img.addEventListener('load', () => {
let imgW = img.width,
imgH = img.height;
atag.dataset.originalSize = `${imgW}x${imgH}`;
console.log('atag:', atag);
});
// load image from atag's href
img.src = atag.href;
});
<figure>
<a href="https://i.picsum.photos/id/1077/200/300.jpg">
<img src="https://via.placeholder.com/40" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/913/200/200.jpg">
<img src="https://via.placeholder.com/50" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/1058/100/100.jpg">
<img src="https://via.placeholder.com/60" />
</a>
</figure>