Search code examples
jqueryimagesrconerror

bind onerror with dynamically created image tag in jquery


i am trying to bind the onerror of img with a function. image tag is created like this in jquery

this._img1 = $("<img>");

this is the function

function imgError(image) {
  image.onerror = "";
  image.src = '/Content/img/placeholder-profile.jpg';
  return true;
}

now i want to bind this function with onerror ... i've tried following things and they wont work for me

this._img1.on("onError", "imgError(" + this._img1 + ")");

and

this._img1.prop("onError", "imgError(this)");

and

this._img1.error(function () {
    _img1.src = '/Content/img/placeholder-profile.jpg';
});

can anyone suggest me how can i achieve it ?


Solution

  • Well, in my own case, I simply registered a global listener for the onError event like so:

    $("img").on('error', function() {
      $(this).attr("src", "/path/to/my/default/placeholder-image.png");
    });
    

    This took care of all broken image links. In your case, you can use either/both #id and/or .class selectors to narrow down to specific elements.

    The jquery .on() function works for dynamically created elements, too. See sample here