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="http://www.w3.org/1999/xhtml">
<head>
    <title>Default Image Load Demo</title>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js" 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
            loadImage(image);
        });

        //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);
                });
            }
        }
    </script>
</head>
<body>
    <div>
        <img src="#" alt="Image Load demo" id="ImageControl" />
    </div>
</body>
</html>

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

1

 

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

2

Happy Coding.!!

You may also like...