Home > Web Front-end > JS Tutorial > How to Load Images Dynamically from a Folder Using jQuery/JavaScript?

How to Load Images Dynamically from a Folder Using jQuery/JavaScript?

Susan Sarandon
Release: 2024-11-03 19:04:03
Original
630 people have browsed it

How to Load Images Dynamically from a Folder Using jQuery/JavaScript?

Loading Images Dynamically from a Folder Using jQuery/JavaScript

Navigating folders to load assets like images can be challenging when their names are non-sequential. However, jQuery provides a solution to retrieve and display images from any directory.

Solution:

Implementing this solution involves utilizing an AJAX call to fetch the content of the target folder:

<code class="javascript">var folder = "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 +"'>" );
            } 
        });
    }
});</code>
Copy after login

This approach uses jQuery to parse the HTML response from the AJAX call. It then iterates over the anchor tags within the response, filtering out only those ending with supported image file extensions. Finally, it dynamically appends these validated image paths to the DOM.

Note:

For this solution to work effectively, it's crucial to configure your server to allow folder listings. In Apache servers, the option "Indexes" should be enabled. For Express.js and Node.js, an external package named "serve-index" can be utilized to achieve the same functionality.

The above is the detailed content of How to Load Images Dynamically from a Folder Using jQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template