Search code examples
jqueryhtmlsrcmailto

Why isn't my icon changing after "src" attribute on image?


I have the following code when i click on an image where the id is "mailToTechOwner"

$('#mailToTechOwner').live('click', function (e) {
    e.preventDefault();

    var origSource = $(this).attr("src");
    var objDiv = $(this);

      //change image to ajax loader
    objDiv.attr("src", "/Content/Images/ajax-loader.gif");

    $.get("/Project/MailMessage/" + projectId, function (data) {

        //change image back to original
        objDiv.attr("src", origSource);
        window.location = 'mailto:' + data.Email+ '?subject=Alert' + data.Name;
    });
});

When i step through the code in firebug it works fine but when i run it, my email client pops up (outlook in my case) but the image is still the ajax loader . . even though this line has already run:

objDiv.attr("src", origSource); 

is there anyway to not popup the email until the image change is complete ? Is changing the src attribute an async action? Is there some callback to ensure its completed before running other code?


Solution

  • Instead of replacing the image source, try having both images in the HTML, and just initally hide the loader.

    On the GET request just hide the original image and show the loader, and on completion redo it. You could also do something like :

    $(document).on('click', '#mailToTechOwner', function(e) {
        e.preventDefault();
        var loader = $('<img src="/Content/Images/ajax-loader.gif" />'),
            img = $(this)
    
        img.hide().after(loader);
    
        $.get("/Project/MailMessage/" + projectId, function (data) {
            loader.remove();
            img.show(1, function() {
                window.location = 'mailto:' + data.Email+ '?subject=Alert' + data.Name;
            });
        });
    });
    

    Where you change the documents location in the native jQuery callback in show().