Search code examples
javascriptimageloadinggifpreview

How to show loading gif while image preview loading via javascript


On my page i am using links with image preview.

When you go on link with mouse it show a preview image.

Here is demo : http://cssglobe.com/lab/tooltip/03/

i want to show loading gif while image preiview loading.

Loading gif like this : https://i.sstatic.net/0R9Up.gif

here is my javascript code ;

this.screenshotPreview = function(){   
        /* CONFIG */

                xOffset = 10;
                yOffset = 30;

                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result

        /* END CONFIG */
        $("a.screenshot").hover(function(e){
                this.t = this.title;
                this.title = "";       
                var c = (this.t != "") ? "<br/>" + this.t : "";
                $("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");                                                                
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");                                               
    },
        function(){
                this.title = this.t;   
                $("#screenshot").remove();
    });
        $("a.screenshot").mousemove(function(e){
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px");
        });                    
};


// starting the script on page load
$(document).ready(function(){
        screenshotPreview();
});

and html codes ;

<a href="Link" class="screenshot" rel="image link">Link Name</a>

so how can i do ? Any ideas ?


Solution

  • You could use a variation of the following code snippet to trigger an event once it's loaded:

    var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
        .load(function() {
            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                alert('broken image!');
            } else {
                $("#something").append(img);
            }
        });