For new dynamically inserted elements you can do it using MutationObserver
. And for the remaining images just get them and add the event.
var observer = new MutationObserver(
function(mutations)
{
for (var m in mutations)
{
var mutation = mutations[m];
if (mutation.addedNodes) // todos nodos adicionados
{
for (var i = 0; i < mutation.addedNodes.length; ++i)
{
var node = mutation.addedNodes[i];
if (node.nodeName == "IMG") // se for imagem
{
// adiciona o evento "error"
// caso o erro ocorra, a classe será adicionada
node.addEventListener("error", function() {
node.className += " failToLoad";
}, false);
}
}
}
}
}
);
// inicia o observer
observer.observe(document, { childList: true, subtree: true });
And for elements already on the page:
$(function() { // quando a página carregar o DOM
// para todas imagens da página
$("img").each(function(i,e) {
// adiciona o evento
e.addEventListener("error", function(imgEvents) {
var img = e;
e.className += " failToLoad"; // em caso de erro adiciona classe
}, false);
});
});
See this example in jsFiddle . Note that dynamically inserted images are also validated. In this example the script is being inserted between the <head>
tag.
Note that if the image is external, eg imgur, and you pass an invalid link, the site will not generate the 404 error instead it will generate a default image.