About

Labels

slider

Recent

Navigation

Broken image handling using jQuery and Javascript

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.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: