'image height coming back as 0 -- need to get the height after the image loads
I'm enlarging an image on click. I'd like to put a caption right under the image, but to do that, I have to know what the new rendered height of the image is after it's enlarged. I don't want the "natural height" of the image. How do I do that?
html:
<img src="img/img-url.jpg" class="enlarge">
<div class="caption">my caption is here</div>
<div class="popup ">
<img src=""/>
<div class="caption"></div>
</div>
css:
.popup {
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
z-index: 9999;
width: 100%;
background-color: rgba(0,0,0,.9);
height: 100%;
display: none;
}
.popup img {
max-width: 90%;
max-height: 90%;
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
}
.popup .caption {
position: fixed;
width: 100%;
text-align: center;
left: 0;
}
jquery
$('.enlarge').on('click', function(e) {
var thisImg = $(this).attr('src');
var thisCaption = $(this).next().text();
$('.popup img').attr('src', thisImg);
var imgH = $('.popup img').height(); //returns 0 because loads asynchronously
$('.popup .caption').css('top', imgH + 10);
$('.popup .caption').text(thisCaption);
$('.popup').fadeIn();
});
Solution 1:[1]
You dont really need to know the height of the image to put the caption at the bottom of the image. Modify your css and change .popup img and caption position to relative. Here is the modified code:
$('.enlarge').on('click', function(e) {
var thisImg = $(this).attr('src');
var thisCaption = $(this).next().text();
$('.popup img').attr('src', thisImg);
$('.popup .caption').text(thisCaption);
$('.popup').fadeIn();
});
.popup {
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
z-index: 9999;
width: 100%;
background-color: rgba(0, 0, 0, .9);
height: 100%;
display: none;
padding-top: 20px;
}
.popup img {
max-width: 90%;
max-height: 90%;
position: relative;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
}
.popup .caption {
position: relative;
width: 100%;
text-align: center;
left: 0;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.stack.imgur.com/HI86p.png" class="enlarge">
<div class="caption">my caption is here</div>
<div class="popup ">
<img src="" />
<div class="caption"></div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dan Sherwin |