2

Alright so i need to know if its possible to alert the user that the url of the image is invalid (assuming they have entered it incorrectly).

What the code does is that the user enters the image number. Presses display and the image will show below so they can download.

The image is provided bya website, that is why if the image code is incorrect, the user must be alerted.

Please run the code snippet.

For a legit image enter 63700 on the textbox.

Now enter a random number or word... nothing shows up? the user needs to be alerted. I hope i'm making sense.

function myFunction() {
  var x = document.getElementById("imagetxt").value;
  var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg"
  document.getElementById("image1").src = y;
}
<!DOCTYPE html>

<html>

<head>
</head>

<body align="center">
  <form>
    <input id="imagetxt" size="6" type="text" value="">
    <input type="button" value="Display" onclick="myFunction()">
  </form>
  <img id="image1" src="" width="50%" height="50%">
</body>

</html>
L3SAN
  • 61
  • 1
  • 8
  • 1
    Possible duplicate of [Check if image exists on server using JavaScript?](http://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript) – nicael Dec 20 '15 at 10:00
  • [And the most convenient way in the linked question](http://stackoverflow.com/a/18837818/). – nicael Dec 20 '15 at 10:05

2 Answers2

1

You should use .onerror and .onload events on the img.

function myFunction() {
  var x = document.getElementById("imagetxt").value;
  var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";

  // Creating an image
  var img=new Image();

  // Defining the function if image loads successfully.
  img.onload=function(){
     document.getElementById("image1").src = y;
  };

  //Defining the function if image fails to load.
  img.onerror=function(){
     alert("Image not found");
  };
  img.src=y;
  
}
<!DOCTYPE html>

<html>

<head>
</head>

<body align="center">
  <form>
    <input id="imagetxt" size="6" type="text" value="">
    <input type="button" value="Display" onclick="myFunction()">
  </form>
  <img id="image1" src="" width="50%" height="50%">
</body>

</html>
void
  • 36,090
  • 8
  • 62
  • 107
0

Here a simple function to check if is image or error

function checkImage (src, good, bad) {
    var img = new Image();
    img.onload = good; 
    img.onerror = bad;
    img. src = src;
}

checkImage( "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-303579.jpg", function(){ alert(this.src + " " + "good"); }, function(){ alert("bad"); } );

checkImage( "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-dsdsds.jpg", function(){ alert("good"); }, function(){ alert(this.src + " " + "bad"); } );
Fahed Alkaabi
  • 269
  • 2
  • 10