Search code examples
javascripthtmlimageonerror

Changing an image src on the fly with Javascript


I'm trying to change the src of some img tags if/when there is a problem with the pics when loading the page. I seem to be getting some random behavior particularly from Internet Explorer 9. Some of the images show the replaced image correctly and some have a red cross on them. If I debug in the browser I'm told that ImgError() is not defined. It's clearly defined in the code and is obviously working. Why is this happening?

<div class="PhotoBorder"><img alt="" onerror="imgError(this)" 
    src="./images/services/69_Staffmember.jpg" /></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">           
    </script>  

<script> 
$(window).load( function() {
    $('.RowWrapper').each(function() {
        var TotalWidth = 0;
        $(this).find('.StaffMember').each(function() {
            TotalWidth = TotalWidth + $(this).outerWidth(true);     
        });
        this.style.width = TotalWidth + "px";           
    });
});

function imgError(img)
{ 
    img.setAttribute("src","./images/services/49_ImgMissing.jpg");  
    img.removeAttribute("onerror");
}     

</script>

Solution

  • I'm answering on behalf of RobG. The definition of imgError() was below where it was being called in my code. You must position your code definitions above where you make calls in your html. Otherwise your results may be undefined as I found out.