0

when the page loads, if the image returns a 404 not found error I would like to remove the wrapping div.item so the carousel continues as if.. how can I achieve this?

this was my logic.. but no luck

$(window).load(function() {
    $(".item img").error(function () { 
        $(this).parent('div.item').remove();
    });
});

bootstrap carousel markup

1 Answers1

1

On the image tag you can add the onerror event

<img src="404imagegoeshere" onerror="functionToRemoveWrapping(this)">

Then on your function you can do something like this

    <script>
         function functionToRemoveWrapping(image) {
           setTimeout(function(){
             $(image).parent().remove;
           }, 2000);    
         }
    </script>

The 2000 value is in miliseconds.

General Electric
  • 1,176
  • 3
  • 21
  • 44
  • how can I force it to wait for jQuery to run? the onerror happens much before. thanks – Telmo Moura Jun 09 '16 at 14:22
  • I edited my answer, I added the setTimeout function which waits x milliseconds before executing the code in its body – General Electric Jun 09 '16 at 14:45
  • doesn't work, no errors but browser's image placeholder is still there. here's what is happening: on the console when I target `$('img').attr("onerror", "functionToRemoveWrapping(this)");`all my images now have this attribute, or any other from the images inside the carousel. -_- – Telmo Moura Jun 09 '16 at 14:56
  • JG Estevez answer is valid because he uses an element that already have that attribute in the DOM when rendered, if you add the attribute via script it its firing after it calls for the image, also if you want to target images inside the carousel only try `$('.carousel img')`, otherwise you are telling jQuery to apply that attribute to all img elements on the DOM – David Ortega Jun 09 '16 at 16:17
  • "on the console" - I said. I'm hard coding the `onerror` in the `img` tag html, but when looking for it in the browser it's all over the DOM in every image on the page not just the carousel ones. I believe it has to do with bootstrap's carousel functionality (also, not sure, but it looks like it duplicates several times the images. and the 404's in this case) And that's why this won't do the job. but I do appreciate your time and efforts. thank you – Telmo Moura Jun 10 '16 at 11:12