Reputation: 1296
I am a bit stuck. I am creating a rotating background image with jquery and css. I resize the image width according to the browser size, but I do not want to change the height because it distorts the picture. So I want to do a simple math equation to make the image vertically centered on the screen. For example: The image has an original size of 1600px and it resizes to 1200px, I need to get the height of the resized image. I have tried this with jquery simple: $("#img1").height(); but it returns the value 0. Here is my jquery, html and css:
HTML
<div id="div2"><img src="images/1.jpg" class="bg" id="img1" /></div>
<div id="div3"><img src="images/1-blur.jpg" class="bg"/></div>
<div id="content">Body Content goes here!!</div>
<script>
var iheight = $("#img1").height();
$("#content").append(iheight);
</script>
CSS body{ padding: 0; margin: 0; position: relative; overflow: hidden; } .bg { width: 100%; position: absolute; top: 0; left: 0; z-index: 1; } #content{ position: relative; z-index: 999; }
And Jquery to rotate images:
$(window).load(function(){
function startfade(){
$("#div3").fadeIn(3000, function(){
$(this).delay(2000).fadeOut(2000);
$("#div2").fadeIn(3000, function(){
$(this).delay(2000).fadeOut(2000);
});
});
}
setInterval(function() {
startfade();
}, 6000);
startfade();
});
Any help on how to get the actual height of the image would be awesome! Thank you so much!
Upvotes: 4
Views: 9105
Reputation: 11
I use this formula, getting the ratio height/width of the original image
var ratio=originalImageHeight/originalImageWidth;
var newHeight=newWidth * ratio;
Upvotes: 0
Reputation: 265
This is the answer of a similar thread I found on stackflow.. hope it helps !
var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
Upvotes: 0
Reputation: 66560
Try to call height when image is loaded (and you should always enclose your code in $(function() {});
so your code is invoked when DOM is ready)
$(function() {
$('#img1').load(function() {
$("#content").append($(this).height());
});
});
Upvotes: 1