morbidCode morbidCode - 7 months ago 38
HTML Question

Checking for visibility of image files

I've recently been asked to create a page that handles image file uploads to the server using ajax and php. The catch is when the file is selected, it should be previewed on the page.

The problem is my eyes are destroyed therefore I cannot validate the image if it is visible or not to the user. To solve, I ended up checking the src attribute for the value, like this:


My question is: Given a certain length and height to the element, will I be certain that as long as the src attribute has a value, a valid image file will be visible? Will it work in all cases? If not, what is the best way to check if the image exists and is visible?


To check the loading state and availability of an image you can use load and error event listener.

$("#img").on("load", function() {
    // the image is successfully loaded
}).on("error", function() {
    // the image could not be loaded, maybe the image is not availbale