JavaScript Image Onload | Image Onload in JS Tutorial By WDH

JavaScript Image Onload


I was recently coding an application that would inject an image into the page and then execute a given function when the image's onLoad event fires. My code was working everywhere except Internet Explorer. That wasn't all together shocking initially but the fact that even IE8 was failing to the fire the onLoad event was discouraging. Here's what my code looked like:

 

var img = new Element('img',{
	alt: this.title ? this.title.get('html') : this.options.url,
	src: this.options.url,
	events: {
		error: function() {
			this.messageBox.set('html',this.options.errorMessage);
			img.dispose();
		}.bind(this),
		load: function() {
			img.setStyle('display','');
			this.unfade();
			if(!this.footer) {
				img.setStyle('cursor','pointer').addEvent('click',this.close.bind(this));
			}
		}.bind(this)
	},
	styles: {
		display: 'none'
	}
}).inject(this.messageBox);

On a hunch I detached the "src" assignment and coded that as a separate statement:

var img = new Element('img',{
	alt: this.title ? this.title.get('html') : this.options.url,
	events: {
		error: function() {
			this.messageBox.set('html',this.options.errorMessage);
			img.dispose();
		}.bind(this),
		load: function() {
			img.setStyle('display','');
			this.unfade();
			if(!this.footer) {
				img.setStyle('cursor','pointer').addEvent('click',this.close.bind(this));
			}
		}.bind(this)
	},
	styles: {
		display: 'none'
	}
});
img.set('src',this.options.url).inject(this.messageBox); //for ie