0

I'm trying to replace the image when it encounters error on the initial src by using this...

$(".thumbnails").on("error", function () {
    if ($(this).attr("src") != "/assets/img/img-error.jpg") {
        $(this).attr("src", "/assets/img/img-error.jpg");
    }
});

It's working fine on images that has been loaded during page load..however when I got images appended in a modal or popover it didn't trigger the function even though I'm using .on() delegation

I also tried using this but it didn't do the function even on images during page load..

$(document).on("error", ".thumbnails", function () {
    if ($(this).attr("src") != "/assets/img/img-error.jpg") {
        $(this).attr("src", "/assets/img/img-error.jpg");
    }
});
saionachi
  • 397
  • 1
  • 5
  • 21
  • Try: `$(document).on("error", ".thumbnails", function () {}` if your DOM elements are not there at run time and added dynamically then they wont be attached to the event. – Bossman Sep 25 '20 at 09:50
  • @Bossman I tried using that but the event did not fire at all even on elements on load o_O weird.. – saionachi Sep 25 '20 at 09:52
  • 1
    You need attach the event handler when you append the image to the appended elements. @RoryMcCrossan error event don't bubble so you can't use it for event delegation. – Mark Baijens Sep 25 '20 at 09:56
  • 2
    This should help you: https://stackoverflow.com/questions/18683503/jquery-on-image-error-not-working-on-dynamic-images/18683695 – Bossman Sep 25 '20 at 10:08
  • @MarkBaijens very good point, duplicate updated – Rory McCrossan Sep 25 '20 at 10:27
  • Thanks @Bossman it worked on images I appended on modals.. now my only problem is the images returned in popover..I'm returning more images when hovering on that thumbnails on page load using bootstrap popover..is there any way to attach event handler for popover image? – saionachi Sep 25 '20 at 10:32
  • 1
    ah, I found a solution to attach event handler on popover contents by using `$(document).on('shown.bs.popover', function() {});` Thanks for the help guys! :) – saionachi Sep 25 '20 at 10:39

0 Answers0