Search code examples
javascriptonloadonerror

Turn an image's onError function into a return


So I need a function to test if an image can load or not. Here's what I've got:

function imgExists(url){
    var img = new Image();
    img.onerror = function(){
        alert('error')
    }
    img.onload = function (){
    alert('load')
    }
    img.src = url;
}

imgExists('http://hashtraffic.com/img/jackson@2x.png')

The issue is that the alerts are trapped in their won functions. How can I get the imgExists() function to return true if the image loads and false if it does not?


Solution

  • You need to use a callback, since your function is inherently asynchronous:

    function imgExists(url, callback) {
        var img = new Image();
        img.onerror = function() {
            callback(false);
        }
        img.onload = function () {
            callback(true);
        }
        img.src = url;
    }
    
    function checkImage(exists) {
        alert("Image exists: " + exists); // Usage example.
    }
    
    imgExists('http://hashtraffic.com/img/jackson@2x.png', checkImage);