Skip to content

Instantly share code, notes, and snippets.

@mykeels
Last active July 7, 2017 05:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mykeels/55c72eaca002dbba5ee9a727937a70b6 to your computer and use it in GitHub Desktop.
Save mykeels/55c72eaca002dbba5ee9a727937a70b6 to your computer and use it in GitHub Desktop.
Specify Default Images in Javascript

Default Image Script

Specify Default Images for your <img> tags to be loaded when their images fail to load.

How to use

Simply place the script in default-src.js at the bottom of your page.

if (jQuery) {
$('img[default-src]').each(function () {
var $elem = $(this);
this.onerror = function () {
if ($elem.attr('src') != $elem.attr('default-src')) $elem.attr('src', $elem.attr('default-src'));
}
});
}
@ezra-obiwale
Copy link

Why not turn the thing into a plugin? Makes it neat for usage.

@ezra-obiwale
Copy link

I think just a method would even do. Below is an untested code:

// default-src.js
(function($){
	$.defaultSrc = function() {
		$('img[default-src]').on('error', function(){
			if ($(this).attr('src') !== $(this).attr('default-src'))
				$(this).attr('src', $(this).attr('default-src'));
		}};
	};
})(jQuery);

Usage would be:

<script src="path/to/default-src.js"></script>
<script>
    $.defaultSrc();
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment