Mostafa Talebi
Mostafa Talebi

Reputation: 9173

Javascript loading an image

I have a field and a container for an image.

In this container there is a default image.

I want the user to put a link of an image and then submit it, this then adds the image to the src attribute of the default image.

My question, how should I load image, and during this time show a progress bar to the user, and after loading finishes, hide the URL. My main concern now is how to load the resource.

Now I have written this script:

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    $("#image-width").attr("src", logoUrl); // and put the URL into the src attribute of the image

});

Though I need something like this:

$.imageLoad({ url : "url/to/image.jpg", 
    complete : function(){
    alert("upload finished!");
    });

I have no problem to writen callbacks and status's, but I don't know how to load a resource.

Thanks in advance

Upvotes: 0

Views: 102

Answers (1)

Andrija Petrovic
Andrija Petrovic

Reputation: 209

You just miss the onload handler. When you set the src attribute on the image (the DOM image element), it begins loading the resource. When the resource is loaded, image will trigger the onload event.

So, instead of

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    $("#image-width").attr("src", logoUrl); // and put the URL into the src attribute of the image

});

do

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    var image = $("#image-width")[0];

    image.onload = function(){alert("upload finished!");}

    image.src = logoUrl; // and put the URL into the src attribute of the image

});

so that you're dealing with the reference to the Image DOM element directly, not with the jQuery reference. Of course, when the resource is loaded, you will have to hide the progress bar etc... not just alert the message.

Upvotes: 1

Related Questions