Reputation:
I have a img tag in a div which is hidden, but when I try to get height and width of that img tag, It gives 0 - 0.
Here is my html
<div style="display:none">
<img id="image" src="https://igcdn-photos-h-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11357782_1454910574825551_630646141_n.jpg">
</div>
jQuery for getting height and width
$(document).ready(function(){
height = $('#image').height();
width = $('#image').width();
alert('Height: '+height+' Width: '+width);
});
CSS
#image {height:200px; width:300px;}
I want to get 200 as height and 300 as width, I can do it with getting css of the element, but the height and width for #image would not be static, It would be in percentage and for that i need to get height and width on runtime without showing the image tag container.
Please help me. Thanks
Upvotes: 0
Views: 356
Reputation: 4288
Another workaround, using jQuery:
$(function(){
var $target = $('#image');
$target.parent().show();
$target.hide().on('load', function(){
alert( $(this).width() + ', ' + $(this).height() );
$(this).parent().hide();
$(this).show();
});
});
Upvotes: 1
Reputation: 167182
You might need to FOUC a few seconds with the jQuery way! If it is okay for you, you can use this:
$(function () {
$("#get-image-size").show();
a = {
height: $("#get-image-size img").height(),
width: $("#get-image-size img").width()
};
$("#get-image-size").hide();
$("body").append(JSON.stringify(a));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="get-image-size" style="display: none;">
<img id="image" src="https://igcdn-photos-h-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11357782_1454910574825551_630646141_n.jpg" />
</div>
Or you may use the new Image()
way in pure JavaScript:
<div id="img"></div>
<script>
var img = new Image();
img.src = "https://igcdn-photos-h-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11357782_1454910574825551_630646141_n.jpg";
img.onload = function () {
document.getElementById("img").innerHTML = '{"height": ' + this.height + ',"width": ' + this.width + '}';
};
</script>
Upvotes: 0