Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image,onload event not working in chrome

I'm using html5 to create drag and drop image upload functionality. This works great for me in firefox but in chrome the image onload event only fires the first time. If I drag multiple images in only the first works and if I drag a second in it fails. I believe the problem is with the image onload.

here is the way my code works I have removed the irrelevant sections:

            var img = document.createElement("img");
            var reader = new FileReader();
            var canvas = document.createElement("canvas");
            var canvasData;
            var ctx = canvas.getContext("2d");
            var myFiles;
            var i = 0; 


                 reader.onload = (function (aImg)
                    { 
                        return function (e)
                        {
                            aImg.src = e.target.result;
                        };
                    })(img);

        img.onload = function (){

        //resizes image 
        //draws it to the canvas
        //posts to server

        i++;
        if(i < myFiles.length){
        processNext(i);
                            }
        }



    function processNext(filei) {

         var file = myFiles[filei];

            img.file = file;

            reader.readAsDataURL(file);


        }

i = 0;
myFiles = files;
processNext(0);

Does anyone know why this works in firefox but not chrome?

like image 562
Early73 Avatar asked Apr 28 '11 14:04

Early73


People also ask

How do I use image onload?

To use the image onload event in JavaScript, you can use the document. querySelector() method or user-defined function. In the first approach, the addEventListener() method is called with the window object used to add an event listener to the document. querySelector() method.

Does Div work onload?

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

Is onload an event or an event handler?

The onload event handler is used to call the execution of JavaScript after a page, frame or image has completely loaded.

Can we use onload in form?

<form> has no "onload", nor should it. if you want to run something onload, then put it on the <body> tag.


1 Answers

Explanation from chromium tracker:

This is not a bug. WebKit is just more strict. You must instantiate a new Image() object before the replacement, like this:

var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;

source: http://code.google.com/p/chromium/issues/detail?id=7731#c12

like image 81
Harut Avatar answered Oct 07 '22 20:10

Harut