0

I have a web page that includes 10's of thousands of images. Sometimes the image isn't available so a broken image is displayed in the clients browser.

The broken image is in the following URL format: www.domain.com/t.php?src=p/dd5e5b08_1.jpg.

How do I use jQuery to get the set of images, filter it to broken images then replace the src?

The following does not work:

above the closing </head> tag

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>

above the closing tag

<script type="text/javascript">
    $(window).load(function() {
        $("img").each(function(){
            var image = $(this);
            if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){
                $(image).unbind("error").attr("src", "/images/no_image.png");
            }
        });
    });
</script>

2 Answers 2

2

This code might help you:

function imgError(image){
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}

<img src="image.png" onerror="imgError(this);"/>

Try CodeFiddle Demo

Sign up to request clarification or add additional context in comments.

3 Comments

how do you set dynamically <img src="image.png" ?
get image on php variable and use it like this: <img src="<?php echo $image ?>">
What is return true for?
0

This may help you:

$(document).ready(function () {
    let images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];
    let image_html = '';
    $.each(images, (key, value) => {
        image_html += '<img src="img/' + value + '"/>';
    });
    $('#imgcontainer').html(image_html);
    $('img').on('error', function () {
        $(this).replaceWith('<img src="img/no-photo.jpg"/>');
    });
});

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.