I have a function resizePreview() that will resize an image in a jQuery dialog box if the image is too big. This image can be changed by the user. My code goes something like this:
$('#imagePreview').attr('src', newImageSrc);
resizePreview();
resizePreview() uses $('#imagePreview').width() and .height() to get the dimensions and resizes accordingly. The problem is that the new image isn't loaded by the time resizePreview() is called so the image is resized according to it's original dimensions, not according to the dimensions of the newly loaded image.
If I put an alert() call in between the two lines of code it works (since the alert gives the browser enough time to load the new image). Apparently I should use an event? Is there an existing event, or is there a way I can make one, for when the image src has changed (sort of like an onChange event, but for that attribute) or for when the new image has completed loading?
The load event works for Images:
$('img.userIcon').on('load', function () {
$(this).toggleClass( 'bigImg', $(this).height() > 100 );
});
Image objects allow attachment of onload event listeners:
var img = new Image;
img.onload = function () {
alert("Loaded");
};
img.src = "dummy-picture.png";
Related
I have a placeholder background image that i want to replace after its loaded.
$.get("BIG-IMAGE-URL").done(function(data){
$('.MY-DIV-CLASS').css('background-image', 'url("BIG-IMAGE-URL")');
});
Does anyone know how to make a simple function like this?
You can load your big image with javascript, and set the CSS background in the load event handler.
var img = new Image(); // Create new img element
img.addEventListener('load', function() {
// set background here
$('.MY-DIV-CLASS').css('background-image', 'url("bigImage.png")');
}, false);
img.src = 'bigImage.png'; // Set source path
Source: MDN Using_images
Additionally, here is a similar solution using jQuery How can I check if a background image is loaded?
I load png image generated by server-side PHP script (chart) to the HTML IMG-element <img id="chart"> using following JS code:
$('#chart').attr('src', 'chart.php');
The PNG-image generation and downloading takes about 1 second, so I want to show gif loader while image is loading. How to implement this feature with JS?
For balance this is very simple to do in plain JS:
var preload = function(element, src) {
var img = new Image();
// Apply onload before applying src attribute to avoid IE prematurely firing
img.onload = function() {
// Replace #chart with image
element.parentNode.replaceChild(img, element);
};
img.src = src;
}
preload(document.getElementById('chart'), 'chart.php?_...');
$('#chart').attr('src', 'chart.php').load(function(){
//something
});
In case the browser caches it, you may way to add something to the query string to break that. Either way, you need to listen for the image's load event, which should be bound before setting its src (in case it's cached):
var target_url = 'chart.php?_=' + (new Date()).getTime();
// Show "loading"
$('#chart').on("load", function () {
// Hide "loading"
}).attr('src', target_url);
Reference:
http://api.jquery.com/load-event/
Note the caveats near the bottom of that reference, referring to the event when working with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
I'm trying to work out how to determine when an svg image has loaded in the browser. I'm using Raphael JS and I've tried:
var image = paper.image(path, 0,0,10,10);
image.node.addEventListener('load', function(){alert("test");});
and:
$('image').on('load')
all to no avail. I've also used "onload" and "onsvgload" none of which work.
Is there away to determine if an svg image has actually loaded?
I even tried loading the image using an Image() object and then calling paper.image() - but I get two calls to the image (instead of using the preloaded image);
ie:
var preload = new Image();
preload.src = imgPath;
preload.addEventListener('load', function () {
image.path = preload.src;
//Now load image in raphael - except this still forces the browser to make another call for the image
});
Any ideas?
Using the onLoad event handler works, with one additional line of code:
var image = paper.image(path, 0,0,10,10);
var image_node = image.node;
image_node.setAttribute('externalResourcesRequired','true');
image_node.addEventListener("load", function() {
console.log("image is loaded!");
})
You need to set the externalResourcesRequired attribute to true. You may read more about it here: http://www.w3.org/TR/SVG/struct.html#ExternalResourcesRequired
I want to load html , and then get the true image height.
$("#cover").html(stuff); //this has the image inside it
$(function(){
console.log($("#cover img").height()); //sometimes it's 0
});
For some reason, height is sometimes 0. Could it be because the image hasn't been fully loaded yet, and JQuery sees it as 0? If so, how do I overcome this? Is there a callback or something when the image is loaded?
You can use the .load() method of jQuery
$('#cover').html(stuff);
$('#cover img').load(function () {
console.log($(this).height());
};
Why do the console.log inside an anonymous function? Have you tried this?
$("#cover").html(stuff); //this has the image inside it
console.log($("#cover img").height());
//locate the image(s)
$("#cover img").each(function(){
//Build a new Image Object outside the DOM
//that way, CSS won't affect it
var img = new Image();
//add a callback when loaded
img.onload = function(){
//your width and height
//img.width
//img.height
}
//use the image src to load
//use attr() to resolve path issues across browsers
img.src = $(this).attr('src');
});
try to using load method method that we can take advantage of to make this work the way we want it too.
The problem we have right now is that, in the Webkit browsers, the jQuery code runs when the DOM is ready and the DOM is ready before the image has been loaded. So the code runs but since there’s no image to get a width of, we get 0 for the image’s width. We can use the load method to make the code wait until the window has loaded entirely before it runs.
$(window).load(function() {
console.log($("#cover img").height());
});
try using attr() to get the height:-
$("#yourElemengtID").attr('height')
Here is a piece of small code i used before hope this will help you
On my displayed image when mouse is in call this function
function MouseIn()
{
var src;
//to get original image size
var img =$(this);// displayed image
var theImage = new Image();// create a cache image
var imgsource =img.attr("src");// take the src of displayed image
theImage.src = imgsource;// give cached image the source of displayed image
var original_height = theImage.height// take height of image from the source
var original_width = theImage.width;//take width of image from the source
// to get the displayed image size
var Image_displaysize_width= img.width();
var Image_displaysize_height= img.height();
}
Don't you mean to do something like this?
jQuery("#myImg")[0].naturalHeight
better still don't use overhead of jQuery when possible.
document.getElementById('myImg').naturalHeight
I'm building a Javascript lightbox and I'm trying to adjust the size once the image has loaded. I'm using the code below, which works fine - it outputs the correct width once loaded.
My problem:
When I refresh, it will load the image instantly from the cache, and it seems to bypass the load. I get an instant zero for the width. Why does this happen?
My code:
var oImage = new Image();
oImage.src = 'http://mydomain.com/image.png';
container.html(oImage);
oImage.onload = function(){
alert(this.width);
}
** Update **
#Alex: This is the code I've tried with your plugin, I assume I'm probably doing something wrong. I'd be eager to get this working because your plugin looks quite good.
container.waitForImages(function() {
var cWidth = $(this).width();
alert("width: "+cWidth); // returns 0 - works first time but not cached
});
// Adding the image to the container for preload
container.html('<img src="mygraphic.png" />');
You need to do a few things...
Check the complete property of the img element.
Attach the load event before setting the src property.
Also, I found creating a new Image and assigning the src there is the best way to determine if the image has loaded or not.
You may want to switch the .html() and the .onload() calls.
If the image is loading from cache, I'm imagining that the .html() call completes before the script has had a chance to attach a function handler to the image's onload event. Therefore, effectively bypassing the load event itself (as the image has already loaded).
If it's still downloading the image (i.e. not cached), there will be more than enough time to call the .onload attach before the image completely finishes rendering.
While you're at it, you may want to do this the jQuery way, just so you're attaching events more similarly to DOM2 than DOM0.
var image = $('<img/>', {
src : 'http://mydomain.com/image.png'
}).load(function () {
alert(this.width);
})
// maybe clear container before if you want
.appendTo(container);
If we're going to have to set the src after the onload, we might as well do this instead:
var image = $('<img/>')
.load(function () {
alert(this.width);
})
.attr('src','http://mydomain.com/image.png')
.appendTo(container)
;
Hopefully that works cleanly.
This answer JavaScript: Know when an image is fully loaded suggests that you should set onload before setting src