How to remove the default image icon

The images in which I am facing the cross sign issue that appears in chrome and IE is a script I want to get from an external java script file (I want something like this). enter image description here

the first image with a cross when the image tag does not find an image from the source. mozilla will handle this very cleverly, but chrome and IE show a cross icon which I don't want ..

I find out a solution that is not generic, I have to pass a transparent image url when the image does not receive an image from the specified url to every image tag. something like that

<img src="i/ibm.png" onerror="this.src='i/1x1trns.png';">

      

but my page has more than 20 images and the whole project is more than 200, so in this case I want to handle this from one external javascript file ...

so anyone who knows about this problem tell me the solution ... Thnx for cooperation

+3


source to share


2 answers


var imgs = document.getElementsByTagName('img');

for (var i = 0; i < imgs.length; i++) {
    (function(img_elem) {
        var img = new Image();
        img.src = img_elem.src;
        img.onerror = function() {
             img_elem.src = 'i/1x1trns.png';
        };
    })(imgs[i]);
}

      



http://jsfiddle.net/Ypa7N/

+1


source


It's a bit messy to have jQuery defined in a tag <head />

, but you need to do that for $.ready

, if you can write your own $.ready

, then it would be just a little bit of code in ours <head />

.

OR

You will need to add jQuery before you have these images.



Try this code

<body>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("img").on("error", function() {
                $(this).attr("src", "i/1x1trns.png");
            });
        });
    </script>
    <img src="not-a-valid-image.png" alt="Logo not found" />
</body>

      

I used this method in one of my projects.

+1


source







All Articles