1

I want to add an onerror function on div.circle_thumb>img event.

Now, I'm added `onerror event each img tag like this.

<div class="circle_thumb" ><img src="some/url" onerror="this.src=url/to/replaced" /></div>

But this bothering me too much.

Can I add this callback globally?

5
  • is the this.src=url/to/replaced exactly the same in all cases? Commented Aug 23, 2016 at 2:02
  • If by "globally" you mean to say the body or HTML element, then the answer is "no" as the error event doesn't bubble. Commented Aug 23, 2016 at 2:04
  • @JaromandaX Yes, all div.circle_thumb>img will be replaced to that url on error. Commented Aug 23, 2016 at 2:09
  • @RobG It means, I wanna add the callback on all div.circle_thumb>img tags. Commented Aug 23, 2016 at 2:10
  • Ah, in that case, pretty simple. Commented Aug 23, 2016 at 2:12

2 Answers 2

3

You can use javascript like this

[].forEach.call(document.querySelectorAll('div.circle_thumb>img'), function(img) {
    img.addEventListener('error', function(e) {
    this.src='../img/logo.png';
  });
});

or in ES2015+

Array.from(document.querySelectorAll('div.circle_thumb>img')).forEach(img => img.addEventListener('error', e => img.src='../img/logo.png'));
Sign up to request clarification or add additional context in comments.

Comments

1

jQuery version:

jQuery.each($('div.circle_thumb > img'), function(index, image){
    image.addEventListener('error', function(e) {
        image.src='../img/logo.png';
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.