Broken Image Fix with jQuery

broken-image-fix

Now and then we’ll find broken images in our websites, it may because we linked to an image URL that is now invalid, or the file path was incorrect.

We can manually replace the broken images one by one, but what if your site has hundreds or thousands of posts? That could be a lot of headaches.

A simple jQuery fix may help.

$('img').on ( 'error', function(){
    $(this).attr('src', 'path/to/placeholder-image.png');
});

This piece of code will replace all the missing/broken images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.

Reference:
https://api.jquery.com/error/

Save

Author: Leo

My name is Leo who's behind this blog. I've been working with wordpress since 2010. I'll write about themes, plugins, tutorials and all about wordpress here. Hope you find it useful!

Leave a Reply

Your email address will not be published. Required fields are marked *