How to #2 – How to load default image when an image not exists or load failed

In this How to #2, We are going to see how to load a default image when an image not exist and also when an image loading failed using JavaScript.

<!DOCTYPE html>
<html xmlns="">
    <title>Default Image Load Demo</title>
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var url = $(location).attr('href');
            var decodedUrl = decodeURIComponent(url);

            //Get the image name from the query string
            var image = getParameterByName('image', decodedUrl);

            //Calling load image function

        //Read the query string and return the parameter values by name
        function getParameterByName(name, url) {
            return (new RegExp('[?|&]' + name + '=([^&;]+?)(&|#|;|$)').exec(url) || [, ''])[1].replace(/\+/g, '%20') || null;

        //Load the image based on the given image name.
        function loadImage(image) {
            var $imageControl = $('#ImageControl');
            var defaultImageSource = 'Images/default.PNG';

            if (image === null || image === '') {
                //Set default image as source when image name is null or empty
                $imageControl.attr('src', defaultImageSource);
            else {
                var imageSource = 'Images/' + image;
                $imageControl.attr('src', imageSource);

                //Set default image as source on image load failed
                $imageControl.error(function () {
                    $(this).attr('src', defaultImageSource);
        <img src="#" alt="Image Load demo" id="ImageControl" />

Now let us see the output by passing an image name for the query string parameter image.



and now let us see by giving some other image name which doesn’t exists in the current file system.


Happy Coding.!!

You may also like...