JQuery - waiting until image loaded not working - javascript

I need to get the height of an image on the page and try to do so only after the image has been loaded. However, it seems like I'm still getting a height of 0 for some of the images on the page. Here's my code:
carousel_img.on('load', function(){
setCarouselImageMargins(carousel_img, carousel_width);
});
function setCarouselImageMargins(image, width){
var carousel_left_margin = (image.width()-parseInt(width))/2*-1;
image.css('margin-left', carousel_left_margin);
console.log('carousel image width: ' + image.width()); // this is returning 0
console.log('carousel_left_margin: ' + carousel_left_margin);
}
Is there another way to ensure the image is fully loaded on the page?

you can do it after
$( document ).ready(function() {
setCarouselImageMargins(carousel_img, carousel_width);
});

You can use clientWidth and clientHeight DOM properties to get the inner dimension of a DOM element in your case image. So in your scenario, it will get the actual dimension of the visible image
var image = document.getElementById('imageid');
//or however you get a handle to the IMAGE
var width = image.clientWidth;
var height = image.clientHeight;

Related

Get constant browser height and width

I was wondering how I could constantly get the current browser's height and width. Right now, I am using jQuery and have something like this:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors. How should I be checking the dimensions at all times? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!). Please let me know what I can do!! Thanks!
Use a window.onresize function as well as a window.onload handler to update the width and height variables.
(Resizeable Demo)
var width,height;
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
Using jQuery objects it would look like this.
(Resizeable Demo)
var width,height;
$(window).on('load resize', function() {
width = this.innerWidth; // `this` points to the DOM object, not the jQuery object
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
$(window).on("resize",function(){
console.log($(this).height() + " " + $(this).width());
});
fiddle
Try this
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use
window.resizeTo(width, height);
You can trigger the resize function using:
$( window ).resize(function() {
//....
});
Hope it helps you
You can use this to detect a change in screen size:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height and width were declared in a scope that the function has access to. Otherwise make sure to place var before each variable.

jquery .height() is not returning the real value after the append function just called

I am trying to vertically align middle some pics using jquery.
Here is my code
$(".scroll a").hover(function (evt) {
$("#box a").empty().append(
$('<img src='+this.href+' class="loadimg">')
);
vertical_align();
});
while the vertical align function is here
function vertical_align(){
var child = $(".loadimg").height();
var parent = $("#box").height();
var margin = (parent - child)/2;
$("#box a").children("img").css('margin-top', margin);
}
Now the problem i am facing is that when the page is loaded, the imageHeight gives zero and the margin of the pic becomes half of the parent height which mean that imageheight is returning zero. But this only happens for the first time hover on each image.
this happens probably because you're reading the height too early, when at the first request the image isn't fully loaded. You should wait the load (or complete, from the 2nd request of the same image) event for the image, like so
$(".scroll a").hover(function (evt) {
var node = $("#box a");
node.empty();
$('<img src='+this.href+' class="loadimg">')
.appendTo(node)
.one('load complete', function() {
vertical_align();
});
});

set the width dynamically of element which create dynamically

I create one div#sresult_container dynamically and append no of div to that div. and all appended div have different text. so i can retrieve the width of div#sresult_container but i try to that increase the width of div#sresult_container 10px before it display on the view port. how can i do this plese help me?
my code is below:
var $sresult_container = $('<div id="sresult_container"></div>');
AND after that i append the some divs as children of div#sresult_container.
and append to body.
$('body').append($sresult_container);
var Setwidth = $('#sresult_container').outerWidth() + 10;
$('#sresult_container').css('width',Setwidth + 'px');
so here first load original width after that load the modified width. so how can do directly load the modified width.
First of all #sresult_container must have a pre-defined width.
#sresult_container {
width: 100px;
}
$('<div id="sresult_container">text</div>').appendTo('body');
$('#sresult_container').css('width', function () {
return ($(this).outerWidth(true) + 10) + 'px';
});​
http://jsfiddle.net/xBZT7/14/
http://jsfiddle.net/xBZT7/15/

jQuery calculate img's real height / width values which coming from server

I am in a situation that; need to calculate image's original width and heigth values when one of them defined 0 on css. I can't change CSS with jQuery, need to solve like this:
Here is example link.
CSS:
img { width:0px; }​
jQuery:
var imgHeight = $('img').height();
alert(imgHeight);//which returning 0 ofcourse
I hope this is possible with less code, thanks,
Try this:
var img = $("img")[0];
alert( img.naturalWidth + "x" + img.naturalHeight );
http://jsfiddle.net/mjaA3/50/
You could clone the element to a new hidden DOM node (I assume you want to hide it here). Then remove the CSS, then measure the dimensions.
var img = $('img'),
imgHeight = img.css("width","auto").height();
img.css("width","0");
alert(imgHeight);
Here is a fiddle. All we do is temporarily set the height to it's automatic value (which is the image's 100% width), grab the height, and reset the image to width:0;.
EDIT: Since you can't manipulate CSS directly, you can change the class:
var img = $('img'),
imgHeight = img.addClass("auto").height();
img.removeClass("auto");
alert(imgHeight);​
And the CSS:
img {width:0;}
img.auto {width:auto;}​

Google Chrome incorrectly reporting width and height for images during load

Chrome is wrongly reporting width and height values for images during, or just after, load time. Jquery is used in this code example:
<img id='image01' alt='picture that is 145x134' src='/images/picture.jpg' />
<script>
var img = $( 'img#image01' )
img.width() // would return 145 in Firefox and 0 in Chrome.
img.height() // would return 134 in Firefox and 0 in Chrome.
</script>
If you put the script in a $(function(){}) function, the result is the same. but if you run the code a few seconds after the page has loaded, chrome returns the correct result.
<script>
function example () {
var img = $( 'img#image01' );
img.width() // returns 145 in both Firefox and Chrome.
img.height() // returns 134 in both Firefox and Chrome.
}
window.setTimeout( example, 1000 )
</script>
Also if you specify the width and height values in the img tag, the script seems to work as expected in both Firefox and Chrome.
<img id='image01' src='/images/picture.jpg' width=145 height=134 />
But as you cannot always control the html input, this is not an ideal workaround. Can jQuery be patched with a better workaround for this problem? or will I need to specify the width and height for every image in my code?
Your quoted code doing it inline is getting a reasonable result, as the image may well not be loaded before your code executes. You said that you put it in an onload handler and that also has the same result. Did you really mean an onload handler? Because I cannot replicate that result. Note that the jQuery ready function is not an onload handler, it happens much earlier than that. To ensure images are loaded, use the image's load event or the window load event. jQuery ready happens a lot earlier than that.
So this should work:
$(window).bind('load', function() {
var img = $("#theimage");
log("Width: " + img.width());
log("Height: " + img.height());
});
...(where log is something that outputs to the page), and this should work:
$(document).ready(function() {
$("#theimage").bind('load', function() { // BUT SEE NOTE BELOW
var img = $(this);
log("Width: " + img.width());
log("Height: " + img.height());
});
});
...but this will not:
$(document).ready(function() {
var img = $("#theimage");
log("Width: " + img.width());
log("Height: " + img.height());
});
...because it happens too soon.
Edit: I really, really should have said in the above: If you're looking the image's load event (rather than the window load event), you need to check to make sure the image hasn't already been loaded, because its load event may have already fired. That would look something like this:
$(document).ready(function() {
var img, imgElement;
// Find the image
img = $("#theimage");
imgElement = img[0];
if (imgElement && imgElement.complete) {
// Already loaded, call the handler directly
loadHandler.call(imgElement);
}
else {
// Not loaded yet, hook the event
img.bind('load', loadHandler);
}
function loadHandler() {
var img = $(this);
log("Width: " + img.width());
log("Height: " + img.height());
img.unbind('load', loadHandler);
}
});
That will call loadHandler at the earliest opportunity, whether the image load won the race or the ready code won the race.
This is not an error. The img element is 0x0 wide until the image is loaded. You should wait until the image is entirely loaded. Try something like this:
$("img#image01").load(function(){
//do things here
});
$('#img2').show(function() {
if( $.browser.safari ){
alert ( $('#img2').width() );
}
});
.load does not work for Chrome dimension so use .show ;)
Did you try to put that code into
$(document).ready(function(){
});
if that doesn't help, use jQuerys .load() function
var $img = $('#image01'),
iwidth = 0,
iheight = 0;
$(document).ready(function(){
$img.load(function(){
var img = $('#image01');
img.removeAttr('width').removeAttr('height').css({width: '', height: ''});
iwidth = this.width;
iheight = this.height;
});
});
$img[0].src = '';
$img[0].src = $img[0].src;

Categories

Resources