LearnFast.Ninja

Display loading image jQuery load example

Create html div element. Create CSS with animated loading. background: url(Loading.gif) no-repeat center center. Write jQuery script that load image when it is loaded jQuery. When the DOM is ready add some settings and once the image has loaded show the picture with fade in effect.

Step 1: Create html div element.

<div id="Contact_Image" class="imageLoader">

</div>


Step 2: Create CSS with animated loading.

.imageLoader {

    width: 320px;

    height: 410px;

    background: url('/Loading.gif') no-repeat center center;

}


Step 3: Write jQuery script that load image when it is loaded jQuery.

$(function () {

    // Settings

    var elementID = 'Contact_Image';

    var imageUrl = '/Contact_Building.jpg';

    $('#' + elementID).css('width', '320px');

    $('#' + elementID).css('height', '410px');

    var img = new Image();

    // Once the image has loaded

    $(img).load(function () {

        $(this).hide();

        $('#' + elementID).removeClass('imageLoader').append(this);

        $(this).fadeIn();

    }).error(function () { // If you want handle error here

    }).attr('src', imageUrl);

});


Working example code: Note you need the images to activate the example.

<!DOCTYPE html>

<html>

<head>

    <title>TheBestData.com</title>

    <!-- imageLoader - START -->

    <style type="text/css">

        .imageLoader {

            width: 320px;

            height: 410px;

            background: url('/Loading.gif') no-repeat center center;

        }

    </style>

    <script type="text/javascript">

        // When the DOM is ready

        $(function () {

            // Settings

            var elementID = 'Contact_Image';

            var imageUrl = '/Contact_Building.jpg';

            $('#' + elementID).css('width', '320px');

            $('#' + elementID).css('height', '410px');

            var img = new Image();

            // Once the image has loaded

            $(img).load(function () {

                $(this).hide();

                $('#' + elementID).removeClass('imageLoader').append(this);

                $(this).fadeIn();

            }).error(function () {

                // If you want handle error here

            }).attr('src', imageUrl);

        });

    </script>

    <!-- imageLoader - END -->

</head>

<body>

    <!-- imageLoader - START -->

    <div id="Contact_Image" class="imageLoader">

    </div>

    <!-- imageLoader - END -->

</body>

</html>


Result:


Tags

jquery

loading