Search code examples
javascriptonerror

Using JavaScript to dynamically change display style in img tags


I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.

image(s) links:

<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">

My JavaScript:

function imgError()
{
    alert('The image could not be loaded.');
    var _aryElm=document.getElementsByTagName('img');  //return an array with every <img> of the page
    for( x in _aryElm) {
        _elm=_aryElm[x];
        _elm.className="photo240off";
    }
}

The style photo240off equals to display:none.

Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.

(the overall script works well, because I get the alert).


Solution

  • Use this to get the image with the error.

    Change to:

    onerror="imgError(this)"
    

    Then the function can be:

    function imgError(el) {
        alert('The image could not be loaded.');
        el.className = "photo240off";
    }