Blogger Ever

Broken image handling using jQuery and Javascript

Broken images is nothing but a unprofessional impression on your visitors. Use these ways to keep broken image off your site.
Broken image handling using jQuery and Javascript

Broken image seems ugly and simply unprofessional on a simply well designed site. But their is no way to find any broken link until it loads. Server errors are common reasons for that, even images from the site which are blocked in some country can give a error link. Therefore I found solutions for 2 different situations.

Solution 1: Using jQuery

.error() : Bind an event handler to the "error" JavaScript event.

The jQuery function we are going to use that actually a alternate to Javascript function onerror function. This one handle errors in many ways, one of them is broken image links.
// Hide broken images
$('img').error(function () {
    $(this).hide();
});
// Change broken images
$('img').error(function () {
    $(this).attr('src', 'missing.png');
});
 On dynamic content jQuery 1.7 have .on() function that attaches event handler on selected elements.
$('img').on('error', function () {
    // Hide broken images
    $(this).hide();
});

Solution 2: Using native Javascript

Here we're using native Javascript function onerror method. Using it directly on tags in the following way:
<img onerror='this.style.display="none"' src='image.png'/>
 The above image tag have simply added the onerror method and will hide the image upon error.
Blogger

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.