Onload() handler not responding in IE - javascript

I'm creating a canvas and using drawImage() to draw an inline svg. Everything works okay but I'm stuck because of the below problem...
My problem is that the onload handler not responding in IE?? Rhis works in FF and chhrome. How do I fix it to work in IE 9 upwards?
img2.onload = function() {
console.log("load");
}
jsFiddle
function createme() {
var test = $('<canvas />', { id : 'mycanvs' })
$('#album').append(test);
var svg2 = document.getElementById('sSource').innerHTML,
vms = test[0], //canvas
ctx2 = vms.getContext('2d');
svgToImage(svg2);
function svgToImage(svg2) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
alert("just before onload")
img2.onload = function() {
console.log("load"); // does not show
}
img2.src = nurl;
}
}

I don't have an IE VM running at the moment, but according to their docs the handler has to be defined before the object itself:
To ensure that an event handler receives the onload event for these
objects, place the script object that defines the event handler before
the object and use the onload attribute in the object to set the
handler.
I don't see why your code wouldn't work in IE, but this fiddle tweaks it slightly so your handler is defined before you create the image object... give this a try:
function createme() {
var test = $('<canvas />', { id : 'mycanvs' });
var onloadHandler = function() {
console.log("load");
};
$('#album').append(test);
var svg2 = document.getElementById('sSource').innerHTML,
vms = test[0], //canvas
ctx2 = vms.getContext('2d');
function svgToImage(svg2) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
img2.onload = onloadHandler
img2.src = nurl;
}
svgToImage(svg2);
}
createme();
https://jsfiddle.net/z769z7af/10/

Related

why is onload event of img not fired?

I attached an onload event to an imgage created by new image();
But the onload event seems to be never fired. The console.log inside the function which should be run when onload is fired is never displayed.
I also tried to use addEventListener instead of .onload. but it doesn't work either.
function init(){
var main_canvas = document.getElementById('main_canvas');
var bg_canvas = document.getElementById('background_canvas');
if(main_canvas.getContext){
var ctx = main_canvas.getContext('2d');
var bg_ctx = bg_canvas.getContext('2d');
let ball = new Image();
let box = new Image();
console.log(ball);
ball.onload = function() {
console.log('positiv');
bg_ctx.drawImage(box,150,100);
bg_ctx.drawImage(box,150,600);
ctx.drawImage(ball,350,125);
}
ball.src = 'ball.png';
box.src = 'box.png';
}
}
window.addEventListener('load', init);
Expected output should be: 1) (because of console.log(ball);) This works fine.
2) output: positiv (because ball.onload is fired) BUT THIS NEVER HAPPENS!!

Cannot get file size after uploading using JavaScript

I need to validate one file field with required width,height and if file has not uploaded using JavaScript but its not happening like this. Here is my code:
<input type="file" name="copImage" id="copImage" class="form-control" value="" onchange="setBackgroundImage(event);">
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
};
console.log('size bg',backImageHeight,backImageWidth);
}
Here I could not get the file height and width. I also to check the if file has not uploaded.
Pu the log statement inside the onload function. This is because you are trying to access the variable outside its scope, else define those variables outside onload function
bg.onload = function() {
var bgLoaded = true,
backImageHeight = this.height,
backImageWidth = this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
DEMO
suppose i have one button and without selecting file if I am clicking
on the file alert should say to select the file.
Seems you cannot do that with onchange event handler because if file is not loaded. nothing has changed and so function wont fire. In that case you can create a variable & update its state on file upload. On clicking of the button check the variable state
var isFileLoaded = false;
function setBackgroundImage(fileValue) {
var url = URL.createObjectURL(fileValue.files[0]);
bg = new Image();
if (fileValue.value !== '') {
bg.src = url;
bg.onload = function() {
bgLoaded = true;
isFileLoaded = true;
backImageHeight = this.height;
backImageWidth = this.width;
console.log('size bg', backImageHeight, backImageWidth);
};
}
}
function buttonClick() {
if (isFileLoaded) {
} else {
alert('No file selected')
}
}
DEMO 2
Hello You just need to log your height and width inside bg.onload function.these are outside of the scope of variables.thats why you not getting the height and width like this
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
Everything is fine in your code, you need to include console.log() within bg.onload block only like this .
function setBackgroundImage(e)
{
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
function isFileSelected()
{
return document.getElementById('copImage').files.length > 0;
}
You can use isFileSelected() function to know whether file is selected or not .

Trigger Events Inside Anonymous Object

I'm trying to create an anonymous object that will append a new canvas element to the DOM. This all works fine, but when I try to register an event with JQuery on the newly appended canvas from within the Object it does not trigger.
I believe it has something to do with the scope, but how would one go about registering these events?
var game_grid;
$(function() {
game_grid = new GameGrid();
});
(function (window) {
function GameGrid() {
this.initialize();
}
GameGrid.prototype.canvas;
GameGrid.prototype.ctx;
GameGrid.prototype.initialize = function() {
// Append Child to DOM element
this.canvas = document.createElement("canvas");
this.canvas.width = $(".game-grid-container").width();
this.canvas.height = $(".game-grid-container").height();
this.canvas.id = "game_grid";
$(".game-grid-container").html(this.canvas);
// Define Canvas' Context
this.ctx = this.canvas.getContext("2d");
// Set Up Touch Listeners
$(this.canvas).on("vmousedown vmousemove vmouseup", function(e) {
alert("Not Triggering!");
});
}
window.GameGrid = GameGrid;
} (window));
So the answer I found was to stray away from JQuery all together and bind the event with the addEventListener function. I'm sure there is a way to do this with JQuery, but I can confirm this works.
(function (window) {
function GameGrid() {
this.initialize();
}
GameGrid.prototype.canvas;
GameGrid.prototype.ctx;
GameGrid.prototype.background_color = '#F0F0F0';
GameGrid.prototype.grid_line_color = '#D9D9D9';
GameGrid.prototype.horizontal_division = 8;
GameGrid.prototype.vertical_division = 8;
/* Public Functions */
GameGrid.prototype.initialize = function() {
// Append Child to DOM
this.canvas = document.createElement('canvas');
this.canvas.width = $('.game-grid-container').width();
this.canvas.height = $('.game-grid-container').height();
this.canvas.id = 'game_grid';
$('.game-grid-container').append(this.canvas);
// Define Canvas' Context
this.ctx = this.canvas.getContext('2d');
// Set Up Touch Listeners
document.getElementById('game_grid').addEventListener('mousedown', function(e) {
alert('triggering!');
});
}
window.GameGrid = GameGrid;
} (window));

Looking for an alternative to the image onLoad [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery or JavaScript: Determine when image finished loading
The problem is known, but I can't find any simple solution:
var img = new Image();
img.onLoad = function() {
console.log("load"); // this event doesn't fire
};
img.src = "img/domino/21.png";
console.log(img.complete); // false
setTimeout(function() {
console.log(img.complete); // sometimes true, sometimes false
}, 10);
I was looking for an implementation of onComplete event, but I can't find anything. Would you help?
The proper spelling of the event handler property is all lowercase .onload, not .onLoad.
var img = new Image();
img.onload = function() {
console.log("load"); // works every time
};
img.src = "img/domino/21.png";
Javascript is case sensitive so you MUST use the proper case for all object properties.
The alternatives besides .onload are to use:
img.addEventListener("load", function(e) {...});
or (in older versions of IE):
img.attachEvent("onload", function(e) {...});
If you're only using one event handler and you aren't using a cross platform library that already abstracts event handlers for you, then using .onload is the simplest.
And, here's a simple cross browser way to add event handlers:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
var img = new Image();
img.onload = function() {
console.log("load");
};
img.src = "img/domino/21.png";
console.log(img.complete); // false
setTimeout(function() {
console.log(img.complete); // sometimes true, sometimes false
}, 10);
In Chrome,Firefox and Safari
var img = new Image();
img.addEventListener('load',function() {
console.log("load");
});
img.src = "img/domino/21.png";
console.log(img.complete); // false
setTimeout(function() {
console.log(img.complete); // sometimes true, sometimes false
}, 10);
Or in IE or Opera
var img = new Image();
img.attachEvent('onload',function() {
console.log("load");
});
img.src = "img/domino/21.png";
console.log(img.complete); // false
setTimeout(function() {
console.log(img.complete); // sometimes true, sometimes false
}, 10);
Are you sure your image at img/domino/21.png exists? The following code works for me in Firebug's console.
var img = new Image();
var onload = function() {
console.log('load');
}
img.onload = onload;
img.src = "http://img.gawkerassets.com/img/17m7otdiw6n8fjpg/original.jpg?" + (new Date()).getMilliseconds();
If you can use jQuery it can be simple:
$('img').load(foo).error(foo);
Or with vanilla javascript:
img.onload = img.onerror = foo;
var img = new Image();
//blah blah...
img.addEventListener("load",function() {
console.log("Loaded!");
});

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Categories

Resources