Checking if image does exists using javascript
javascript
Solution
The general strategy is to use an DOM `Image` object instance, set the `src` property to the URL of the image you want to check (which will cause the browser to fetch and load the image), and then handle the `load` and `error` events to determine existence or absence, respectively.
Here's an example promise-based approach:
function imageExists(url) {
return new Promise(resolve => {
var img = new Image()
img.addEventListener('load', () => resolve(true))
img.addEventListener('error', () => resolve(false))
img.src = url
})
}
const url = 'http://www.google.com/images/srpr/nav_logo14.png'
imageExists(url)
.then(ok => console.log(`RESULT: exists=${ok}`))
// => RESULT: exists=true
Problem
Possible Duplicate: Check if image exists with given url using jquery Change image source if file exists I am throwing the value of an image path from a textbox into boxvalue and want to validate if the image exist using javascript. ``` var boxvalue = $('#UrlQueueBox').val(); ``` I browsed stackoverflow and found the below to get the image width/height, but don't want to use this. ``` var img = document.getElementById('imageid'); ``` How can an I validate if it is really an image from the image path?