Search code examples
javascriptimagevariablesfile-type

Get different image file formats in JavaScript variable


I'm developing my own portfolio website, which is based on JavaScript gallery. The script shows and prealoads images by tracking current position and it works brilliant when it comes to load only one filetype. Here comes extract:

var $current = 1;
var $sourceImage = 'path-to-images/'+$current+'.jpg';
var $newImage = new Image();
$newImage.src = $sourceImage;

But what if in the directory there are more than one filetype, for example: 1.jpg 2.jpg 3.gif 4.png ... ? What's the best way to find extension of file that exists on server and pass it to the variable?

Thanks for any advice.


Solution

  • To check if a file exists with JavaScript you have to send an ajax request:

    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        if (!req) {
            throw new Error('XMLHttpRequest not supported');
        }
    
        // HEAD Results are usually shorter (faster) than GET
        req.open('HEAD', url, false);
        req.send(null);
        if (req.status == 200) {
            console.log('file exists');
        }
        else {
            console.log('file does not exist');
        }
    

    from phpjs.