How to load all the images from one of my folder into my web page, using Jquery/Javascript

Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

var folder = "https://stackoverflow.com/questions/18480550/images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src=""+ folder + val +"">" );
            } 
        });
    }
});

NOTICE

Apache server has Option Indexes turned on by default – if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index

If the files you want to get listed are in /images than inside your server.js you could add something like:

const express = require('express');
const app = express();
const path = require('path');

// Allow assets directory listings
const serveIndex = require('serve-index'); 
app.use('/images', serveIndex(path.join(__dirname, '/images')));

Leave a Comment