0

I am new to JavaScript and am trying simple web design. I have a doubt that how to get no.of image files stored in local image folder using js code.

I would like to get the no. of image files dynamically so that even if we are adding more images in folder any time that also will be displayed on web page.

function parenting {
  var n=3;
  for(var i=1; i<=n; i++) {
    var img1 = document.createElement('img');
    img1.src = 'images/parenting/'+i+'.jpg';
    document.body.appendChild(img1);
  }
}

In above code, i have given n=3 as default no. of image files but it should be taken from image folder by code.

1
  • 3
    JavaScript on the browser itself is a client-sided language, you will need to use Ajax or node.js to do this. Commented Jul 21, 2016 at 7:52

1 Answer 1

5

If you enable directory browsing on your web server for your images location, then you can do an ajax request and iterate over the results:

$.ajax({
  url: "images/parenting/",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        var filename = this.href.replace(window.location.host, "").replace("http://", "");
        $("body").append("<img src='images/parenting/" + filename + "'>");
     });
  }
});

Here's a vanilla JavaScript answer:

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == XMLHttpRequest.DONE) {
    if (xmlhttp.status == 200) {
      var n = (xmlhttp.responseText.match(/jpg/g) || []).length;

      for (var i = 1; i <= n; i++) {
        var img1 = document.createElement('img');
        img1.src = 'images/parenting/' + i + '.jpg';
        document.body.appendChild(img1);
      }
    }
  }
};

xmlhttp.open("GET", "images/parenting/", true);
xmlhttp.send();
Sign up to request clarification or add additional context in comments.

2 Comments

I like the idea, but I would not suggest to add jQuery to your project only for a simple ajax request...
Fair enough. I've added a vanilla JavaScript approach to my answer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.