I encounter a problem while performing changes on an img element via javascript:
I build a framework to cycle through different images via the arrow keys of the keyboard. I do this by loading all image urls into an array and then changing the src attribute of the img element accordingly.
So far everything works fine. But now I want to display the naturalHeight and naturalWidth of the current image. Unfortunately when I cycle through the images the sizes of the image preceeding the current image is displayed, although the element shows the correct image.
has this something to do with load order and rendering?
I would be very thankful if someone could help me on that issue.
best regards
Max
On the comments:
I simply load the images by:
imageLeft.setAttribute("src", imagesOld[rowCounter]);
imageRight.setAttribute("src", imagesNew[rowCounter]);
I have a function for updating the size information:
function updateSizeInformation() {
var imageLeftX = $find("<%= txtXImageLeft.ClientID %>");
var imageLeftY = $find("<%= txtYImageLeft.ClientID %>");
var imageRightX = $find("<%= txtXImageRight.ClientID %>");
var imageRightY = $find("<%= txtYImageRight.ClientID %>");
var imageLeft = document.getElementById("imageLeft");
var imageRight = document.getElementById("imageRight");
imageLeftX.set_value(imageLeft.naturalWidth);
imageLeftY.set_value(imageLeft.naturalHeight);
imageRightX.set_value(imageRight.naturalWidth);
imageRightY.set_value(imageRight.naturalHeight);
}
And a function to fit the image to the parent div:
function fitImagesToContainers() {
var divLeft = document.getElementById("imageContainerLeft");
var divRight = document.getElementById("imageContainerRight");
var imageLeft = document.getElementById("imageLeft");
var imageRight = document.getElementById("imageRight");
if (imageLeft.naturalWidth > imageLeft.naturalHeight) {
imageLeft.setAttribute("width", divLeft.clientWidth);
imageLeft.setAttribute("height", divLeft.clientWidth * (imageLeft.naturalHeight / imageLeft.naturalWidth));
} else if (imageLeft.naturalWidth < imageLeft.naturalHeight) {
imageLeft.setAttribute("height", divLeft.clientHeight);
imageLeft.setAttribute("width", divLeft.clientHeight * (imageLeft.naturalWidth / imageLeft.naturalHeight));
}
}
When you set the "src" attribute of an image element the page has not loaded, it normally instigates an asynchronous retrieval of the image file resource. After the image onload event fires the image element properties should represent that of the retrieved image, but be unpredictable before then.
If the code you provided executes synchronously it will run into the problem you report.
In Mozilla Firefox (at least) the image attributes can be that of the previous image if inspected immediately in the same script execution, because the new/next image has yet to be retrieved. Exactly what happens if the page has previously loaded the same image may be unpredictable - I found it giving correct dimension values immediately.
I tested this with standard javascript and do not wish to suggest how to program onload event handlers in jQuery . I did come across this other StackOerflow question on javascript, image onload() doesnt fire in webkit if loading same image which may be of interest.
Related
I have a function that displays a different image each time it is called.
function Trial() {
curTrial = increase(curTrial);
//generate the html code
$('#right_wrapper').append(`
<div id="image_holder">
<img id="image">
</div>`)
// present the image
var targetImage = document.getElementById('image')
targetImage.src = stimuli[curTrial];
console.log(targetImage.onload = targetImage.height)
The way i though onload works is that it will not trigger until the src is loaded, but it seems to trigger anyway, and thus result the 0 height for the unloaded image. I've found more threads with similar issues, but none of those I've seen work with template literals.
How can i be sure that targetImage.height always returns the height for the loaded image, instead of 0?
Using javascript, I am adding many pixel images, by moving <image id="myimage" xlink:href="mysource.png" ... /> elements from an XMLdoc to the DOM of an SVG image in a loop, like so
var elems = this.XMLdoc.getElementsByTagName('image');
var elem = elems.item(0);
svg.appendChild(elem);
Sometimes not all of the images are completely loaded, due to network problems, or server limitations.
After loading all images, I would like to check whether that has been successful and, if not, reload the pixel image mysource.png.
I could remove and add back all <image> tags and rely on that the cached images are loaded successfully, but then I would still not know if all images were loaded in the second round.
If it was included with <img> in html, I would do this by checking image.complete, but that does not seem to work for the SVG images.
I am also using Snap.svg to manipulate the SVG. A solution based on this library would be convenient if it can help.
In SVG you listen to the load event through the load event, you can do it like this:
var elems = this.XMLdoc.getElementsByTagName('image');
var elem = elems.item(0);
elem.addEventListener("error", replaceImage);
svg.appendChild(elem);
function replaceImage(e){
var parent = this.parentNode;
var newImage = this.cloneNode();
newImage.addEventListener("error", replaceImage);
parent.removeChild(this);
parent.appendChild(newImage);
}
Hello Stack Overflow community, recently, I've been working on a quick image display using jQuery. It has a list of possible images that can be picked and displayed at random. The issue is, after the page has finished loading, jQuery ceases to detect image load errors for if the image is invalid.
My current method of finding and fixing errors is as follows:
$('img').error(function() {
$(this).attr('src',getImgUrl());
});
This, in normal circumstances such as the page being loaded, picks a valid image, even if multiple invalid images are specified in a row. However, after the page is finished loading, if an invalid image is picked, and fails to load, this function is not even called. Strangely enough though, if I add an onerror attribute to all images, they are always called from the onerror no matter if the page was freshly loaded or not, so why is jQuery having this issue? Any help is appreciated, thanks.
UPDATE:
It also appears this is happening to other jQuery functions as well, such as click.
UPDATE:
It would appear to be an issue with jQuery recognizing new elements on a page, such as newly created images.
UPDATE for those asking getImageUrl:
function getImgUrl()
{
var text = (Math.round(Math.random() * 3)).toString();
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return '/' + text;
}
All this does is pick a random URL, which matches occasionally to an image on my web-server that has many many images.
It would appear that jQuery has issues recognizing new elements on the page, so the way I fixed this was instead of deleting and adding images to the page, I just edited the existing SRC of images when doing changes, which strangely enough, the jQuery error function responds perfectly to.
Here's the refresh function I ended up coming up with for all interested:
function refreshImages()
{
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
$('#thumb' + i).attr('src',url);
if(i == 0)
{
$('#fullimage').attr('src',url);
$('.thumb').css('border','2px solid white');
}
}
resize();
}
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
I am having some frustrating javascript timing issues.
FYI, the page is a jsp file and attached to said page is a separate js file and the jQuery CDN file. For troubleshooting purposes, I eliminated all unnecessary content and code and pasted what I needed into separate jsp and js files to troubleshoot this specific problem.
If I could display the html and js someplace, that would be great. But for now, I'll describe it. The page has two buttons, one to load an image and one to toggle a "zoom" feature (more on that later). The user clicks a button, which loads an image using the DOM, specifically innerHTML. This image is surrounded by horizontal and vertical scrollbars. When the user turns on the "zoom" feature, the image records the mouse-click position in an onclick event. So, with this on, the user clicks on the image and a bigger version of the same image is loaded, again, using the DOM and innerHTML. The very last step, the most important one, using the mouse position, the scrollbars will focus and center on the point clicked (using scrollLeft and scrollTop).
This all works flawlessly in IE. However, in non-IE browers (i.e. FireFox), it takes a couple of clicks for the scroll adjustment to catch up to the innerHTML. That is, when the user "zooms" for the first time, the image loads but the scrollbars don't adjust. It takes two more successive clicks for it to work the same as in IE. I was researching innerHTML and it is slower in FireFox than IE.
How can I fix this? Has anybody else tried to load an image in FireFox using JavaScript and immediately adjust the scroll positioning on the image? Again, it works the first and each time after that in IE. But non-IE browsers are having issues.
I've tried using innerHTML, replaceChild, appendChild, nothing I tried so far fixes it.
Thank you.
Update: I wanted to see if this issue is anything inside the scrollbars or just images; so, I replaced the image with < p > ... < p > and programmed it to scroll immediately after the **first* image is loaded, via a user-initiated onclick event. Interestingly, it worked. I then replaced the text with the image and it was broken again.
So, after an image is loaded using the DOM (i.e. innerHTML), any attempts to programmatically scroll in non-IE browsers will break. If you programmatically scroll once more, though, it will behave normally.
Update2: I tried employing methods to programmatically cancel the event at the end of the call and immediately call the function again, but that didn't fix the issue.
Then, I tried loading the image using jquery and that seemed to work. I adapted it from two other stackoverflow articles: Can I get the image and load via ajax into div and img onload doesn't work well in IE7 (to circumvent a caching issue).
Here is the code I used:
image = new Image();
image.src = "sample.gif?d=" + new Date(); // passing unique url to fix IE (see link above)
image.onload = function () {
$("#imgcontainer").empty().append(image);
// document.getElementById("imgcontainer").appendChild(image); // This worked, too
// $("#imgcontainer").html("<img src=\"sample.gif?d=" + new Date() + "\"></img>"); // Failed
// document.getElementById("imgcontainer").innerHTML = "<img src=\"sample.gif?d" + new Date() + "\"></img>"; // Failed
$("#imgcontainer").scrollTop(25);
};
image.onerror = function () {
$("#imgcontainer").empty().html("That image is not available.");
}
$('#imgcontainer').empty().html('Loading...');
The key, I believe, was using the onload method. I tried employing jQuery.html() inside the onload method and it didn't work. So, that confirms there was definitely a timing issue related to innerHTML and how and when the image is loaded into the DOM. And the onload method, in combination with either the DOM's native appendChild method or jQuery's equivalent appendChild implementation, fixed the problem.
Update3:
Regarding mrtsherman's suggestion below--
Here is my code:
var outerDIV, innerDIV, html;
outerDIV = document.createElement("div");
outerDIV.id = "content";
document.getElementById("body_id").appendChild(outerDIV); // attach div to body
innerDIV = document.createElement("div");
innerDIV = "ImageHolder";
image = new Image();
image.src = "sample.gif?d=" + new Date();
document.getElementById("content").appendChild(innerDIV);
document.getElementById("ImageHolder").style.height=image.height + "px";
document.getElementById("ImageHolder").style.width=image.width + "px";
html = "<img src=\"sample.gif\"></img>";
$("#content").scrollTop(100);
$("#ImageHolder").html(html);
I created an inner div to place the image. After creating said div, I adjusted it's size, based on the dimensions of the image. I adjusted the scrolling in js and then attached the image to the DOM, via innerHTML, and it did not scroll. I changed the width and height to some fixed size larger than the image and it scrolled. But that is not the desired affect, to make a container bigger than the image. Thank you for your help.
Update4:
What is the equivalent of the code I wrote in Update2 when using document.createElement("img"), instead of new Image()? The onload event is not having the same affect as in the Image object; the onload event is an important ingredient, here.
Thank you.
If you know the new images dimensions then I would send those first. Then you can resize a container for the image, adjust scrollbars and then get the image.
Please see the original question, Update2, for the solution I employed.