0

I have a mouseover area where an image pops up via jquery. I would like to test if the external image exists. If yes show it as usual, if not just show a noimg.png.

My code:

 var image = new Image(); 
 image.src = urllink;
 var imagewidth = image.width;
 if (imagewidth == 0) {
   $('#cardpicture').attr('src', ".../noimg.png");
  } else
    {
       $('#cardpicture').attr('src', urllink);
    }

It seems to work only on the second mouseover. So the check is correctly, but I have to move the mouse twice in the "mouseover" area to show up the picture if it exists. In the first "mouseover" event it always shows the noimg.png. What I am doing wrong?

I just tried it with the .ajax and head method but figured out it would just give an error because the pictures are external pictures (and not located at my server).

I just can imagine that it maybe related with the "loading delay" of the external picture.

best greetings and thanks in advance!

hillcode
  • 150
  • 1
  • 10
  • https://stackoverflow.com/questions/8124866/how-does-one-use-the-onerror-attribute-of-an-img-element – User863 Mar 30 '19 at 09:54

1 Answers1

1

if someone is interested in the solution... I finally found it:

// test if image exists --------------:
loadImage(urllink);

function loadImage(src) {
    var image = new Image();
    image.onload = function() {
        if ('naturalHeight' in this) {
            if (this.naturalHeight + this.naturalWidth === 0) {
                this.onerror();
                return;
            }
        } else if (this.width + this.height == 0) {
            this.onerror();
            return;
        }
        // At this point, there's no error. Picture is available:
        $('#picture').attr('src', urllink);
        $('.image-content').css("display", "flex");
    };
    image.onerror = function() {
        //display noimg.png
        $('#picture').attr('src', ".../noimg.png");
        $('.image-content').css("display", "flex");
    };
    image.src = src;
}
hillcode
  • 150
  • 1
  • 10