Search code examples
javascriptimageonerror

What is the opposing event for onerror


I have an image which is being updated by changing the src of the image with javascript. I added an error event listener to test if the image is broken and then reload the image if it is. But if it isn't broken, I want to remove the error event listener. Can't seem to figure out the right event that is an opposite to onerror while dealing with image.

<img src="path/to/img.jpg" id="img">

<script>
var img = document.getElementById('img');
var imgURL = "/path/to/new_img.png";
img.addEventListener('error', refresh);
img.src = imgURL;

function refresh(e) {
    img.src = imgURL;
    if(e.type !== "error") img.removeEventListener('error', refresh);
};
</script>

The last statement e.type !== error still falls within the error function and thus remains false. I need something i can call on if the event does not generate error. Somewhat like onsuccess if there's anything like that.


Solution

  • The opposite, for this specific case, is the load event indicating that the image loaded. I'm rather surprised to not find documented on MDN.

    var img = document.getElementById('img');
    var imgURL = "/path/to/new_img.png";
    img.addEventListener('error', refresh);
    img.addEventListener('load', refresh); // ***
    img.src = imgURL;
    

    then

    function refresh(e) {
        img.src = imgURL;
        if (e.type !== "error") {
            img.removeEventListener('error', refresh);
            img.removeEventListener('load', refresh);
        }
    }
    

    You might add some timeout and/or delay logic there, since otherwise this will constantly re-request the image until/unless it succeeds (which it may never do, if the URL is invalid).