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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 15:21:031049browse

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

Loading Images from a Folder into a Web Page Using jQuery/JavaScript

Question:

How can we dynamically load all images from a specific folder into an HTML page using jQuery/JavaScript, even when the image names are not sequential?

Answer:

To achieve this, we can utilize AJAX and a clever technique to identify image files within the desired 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>

Explanation:

Note:

  • For this to work, ensure that the server has "Option Indexes" turned on.
  • If using a server like Express for Node, you may need to install and use a package named serve-index to enable file listings.

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

Statement:
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