Lee
Lee

Reputation: 137

Count images in directory from js file

I have an image loading function in a js file.

It loads images from 1.jpg to a specified number (let's say 20).

What I would like to do instead of specifying a number, is find out how many images are in the folder and then use that as the specified number.

I know it is possible using GLOB in PHP, but AFAIK you can't use PHP in a js file?

function loadpics(url){

var txt,i,j;

j=20

//j=count(glob("images/" + url + "/*",GLOB_BRACE)); PHP file count here.

txt= "<span id=\"lar\">&laquo;</span><img  id=\"main-img\" src=\"images/" + url + "/1.jpg\"/><span id=\"rar\">&raquo;</span><div id=\"scroller\">";

for (i=1;i<j;i++)
{
txt += "<img src=\"images/" + url + "/t/" + i + ".jpg\"/>";
}

document.getElementById("sidebar-b").innerHTML=txt + "</div>";

}

So how can I get the number of files from the url I pass to my loading picture function?

Or is there a better way?

Upvotes: 4

Views: 2560

Answers (1)

Chinoto Vokro
Chinoto Vokro

Reputation: 978

Instead of relying on the pictures being sequentially ordered, use a foreach loop or create a script that merely echos the filenames as JSON for javascript to request

<?foreach(array_map('basename',glob('memes/*.jpg')) as $value){?>
    <img src='memes/<?=htmlentities($value,ENT_QUOTES|ENT_XML1|ENT_SUBSTITUTE,"UTF-8",true)?>' style='height:200px;'/>
<?}?>

or

<?
if(isset($_GET['pic_list'])){
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(array_map('basename',glob('memes/*.jpg')),JSON_PRETTY_PRINT);
    exit;
}
?>
<div id='pic_list'></div>
<script>//<![CDATA[
    (()=>{
        var
            xhr=new XMLHttpRequest()
            ,list=document.getElementById('pic_list');
        xhr.onload=()=>{
            var frag=new DocumentFragment();
            xhr.response.forEach((v)=>{
                var img=document.createElement('img');
                img.src='memes/'+v;
                img.style.height=200;
                frag.appendChild(img);
            });
            list.appendChild(frag);
        };
        xhr.open("GET","?pic_list");
        xhr.responseType="json";
        xhr.send();
    })();
//]]></script>

Upvotes: 1

Related Questions