Jquery | Check if image exists for the url created at runtime

|
| By Webner

Suppose a website page displays the list of subjects along with information and corresponding image. Html “div” with classname “.subjects” are generated dynamically in accordance with database records of subjects with custom attribute assigned as “data-subjectid” to each div which represents the unique id of each subject.

Suppose we have images folder where images for the subjects have been saved and our requirement is to set the image as background in a div for each subject. For subjects, which do not have the corresponding image located in the folder we need to show the default image. So how do we know if the image exists in the folder or not?

Method 1. Check the width of image:

var url = window.location.protocol + "//" + window.location.host + "/images/";
$(".subjects").each(function() {
    var data = jQuery(this).attr('data-subjectid');
    var id_div = "#" + $(this).attr('id');
    var image = new Image();
    var url_image = url + data + '.jpg';
    image.src = url_image;

    if (image.width == 0) {
        url_image = url + 'default.png';
        jQuery(id_div).css('background', 'transparent url(' + url_image + ') no-repeat');
    } else {
        var url_image = url + data + '.png';
        jQuery(id_div).css('background-image', 'url(' + url_image + ')');
    }
});

Method 2. Check whether the image can be loaded or there is an error in loading image:

var url = window.location.protocol + "//" + window.location.host + "/images/";
$(".subjects").each(function() {
    var data = $(this).attr('data-subjectid');
    var id_div = "#" + $(this).attr('id');
    var url_image = url + data + '.jpg';
    var image = new Image();
    image.src = url_image;
    image.onload = function() {
        $(id_div).css('background', 'url(' + url_image + ') no-repeat 100% 100%');
    }
    image.onerror = function() {
        url_image = url + 'default.jpg';
        $(id_div).css('background', 'transparent url(' + url_image + ') no-repeat 100% 100%');
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *