MyBB Community Forums

Full Version: Automatically replace broken images?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Bump - is it even possible or is there any easier way, thank you
Probably would require a function. Said function would remove the image element and add a div element.
$('.post_body img').one('error', function() {
  $(this).replaceWith('<div>Image not found</div>');
});

It replaces broken images with a div of your choice. Obviously, as this happens after the page has loaded, you will probably see a FOUC for a couple of milliseconds. Also, ensure you place this code inside a ready() wrapper.
Thank you guys (I added +1 to both). However here is the improved and fully working code - now it supports CSS class. The jQuery error function is used.

Quote:To replace all the missing 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.


In your showthread template right after this code:
lang.editreason = "{$lang->postbit_editreason}";


add this:
$(document).ready(function() {
		$('img').each(function() {
    var img = $(this);

    img.error(function() {
        img.replaceWith('<div alt="error404image" title="Click to open the URL" class="error404">Image not found (error 404)</div>');
    }).attr('src', img.attr('src'));
    });
});	

add this piece of code into your showthread.css (Themes):
/** Image not found (error 404) **/
.error404 {
    display: block;
    background: #e7edf3;
    color: #667d99;
    font-size: 11px;
    font-weight: bold;
    border: 1px dotted;
    border-radius: 3px;
    padding: 5px;
    margin: 10px;
    text-align: center;
}

Here is a working example: https://jsfiddle.net/qz6rs6x4/

Thx to @debute from Stackoverflow.com
That's why I used one() instead of error(): if your replacement triggers an error, it will loop indefinitely. one() prevents that by attaching the error event only once.
(2017-03-20, 02:24 PM)Shade Wrote: [ -> ]That's why I used one() instead of error(): if your replacement triggers an error, it will loop indefinitely. one() prevents that by attaching the error event only once.

Unfortunately the notice was shown only once, after page reloaded it was shown again. Thats why I had to use different code.
Pages: 1 2