Search code examples
javascriptjqueryonerror

Call JavaScript function at Jquery.load


I've a javascript function setErrorImages(), which searches all img tags and and gives them an onerror function. This works great.

I also have a division content with dynamic content by calling de jquery .load function like this, which also works:

$("#content").load("http://example.com/otherpage.php");

But when the new content (otherpage.php) was loaded into the division, the setErrorImages() function doesn't work on the img'es within the new content.

I can call the setErrorImages() function on the otherpage.php, and everything works perfectly, but this way I have to do this on every otherpage, which are a lot.

Is there a way to send a javascript file or function with the jquery .load,
or maybe there is a way to re-execute the javascript function right after the jquery .load.

Kind regards,
Liontack


function setErrorImages(){
    var images = document.getElementsByTagName("img");
    for (var i = 0; i < images.length; i++) {
        images[i].onerror = function(){ setErrorImage(this); };
    }
}

function setErrorImage(image){
    image.onerror = null;
    image.src = 'http://tanuri.eu/images/error.png';
}

Solution

  • $("#content").load("http://example.com/otherpage.php", setErrorImages);
    

    .load() accepts a "complete" parameter:

    A callback function that is executed when the request completes.