Handle all images in a directory without having to access [duplicate]

1

The script below, is responsible for showing a sequence of images at a certain rate of quantity (num), so it is necessary to define a number of images. Check out:

Code

<html>
  <body>
    <script>

     var dir = 'imagens' // Pasta Minhas imagens

      var num = '5' // Limite a mostrar

      window.onload = function(){

      for (var i = 1; i <= num; i++) {

      document.body.innerHTML += "<img src='"+dir+"/"+i+".jpg'>";

        }
    }

    </script>
   </body>
</html>

This routine (code block) has two parameters, the first one is the dir (directory) defined in the markup that will be responsible for storing the images.

The second parameter is referring to the display options, this parameter is a num (number) that has the maximum amount to display on the page


I do not want to set a limit number, I want the script itself to bring up the last image of the

  

NOTE - All images within the directory / folder should follow the same concept, all of which must be named by ordinal numbers, Exemplo: 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg etc... Only then will you be able to display them successfully.

    
asked by anonymous 21.01.2017 / 15:18

2 answers

3

After thinking ... (theoretically) There is a way to do this client-side. It is not at all , advisable.

window.loadPatternImages = function() {

  var _this = this;
  this.fileTemplate = "%.jpg";
  this.fileDirectory = "/images/";
  this.imageIndex = 0;

  this.loadImage = function loadImage(src, index) {
    var image = new Image();
    image.src = src.replace('%', index);
    image.onload = function() {
      _this.imageIndex++;
      _this.loadImage(_this.fileDirectory + _this.fileTemplate, _this.imageIndex);
      //document.querySelector('.loaded-images').appendChild(image);
    };
    image.onerror = function(e) {
        var textNode = document.createTextNode('Loaded ' + _this.imageIndex + ' images from ' + src);
      //document.querySelector('.loaded-images').appendChild(textNode);
      _this.errorOccurred(e)
    };
  };

  this.errorOccurred = function(error) {
    console.log(error);
  };

  this.loadImage(_this.fileDirectory + _this.fileTemplate, _this.imageIndex);

};

What you have to do is create a self-recurring-function that calls itself to make a new image in the DOM and give it src . When this image does load, then load next. If this image does not exist, it returns an error then ending the recursion.

You can then use image to append to the DOM. FiddleJs

However, it is much easier to get a server to tell you what images to load.

    
21.01.2017 / 15:58
0

MoshMage said - "There is a way to do this client-side. What you have to do is create a self-recurring-function" / em>

In a free translation self-recurring-function , that is - recursive function

Well, in JavaScript there are two built-in timer functions, setTimeout and setInterval which can be used to call callback functions after a certain time. Here's an example of using this:


setTimeout(function recursiva() { 

document.body.innerHTML += "."; 

setTimeout(recursiva, 1000); 

}, 1000); 

jsbin - Running Demo


As you can see this code above, it calls the recursiva function which, when processed, makes a call to setTimeout(recursiva,1000); that calls recursiva again after 1 second, thus having almost the same effect as setInterval while remaining more resistant to unintentional errors that may occur.


MoshMage highlighted - "You can then use image to append in the DOM"


So I decided to do it like this:

var numero = 0;

numero++;

var figura = document.createElement('img');

figura.src = "/images/'+numero+'.jpg";

document.body.appendChild(figura);


Now in a pre-mounted structure in auto-recorrente-função it would look like this:

var numero = 0;

numero++;


setTimeout(function recursiva() { 


    var figura = document.createElement('img');

    figura.src = "/images/'+numero+'.jpg";

    document.body.appendChild(figura);


setTimeout(recursiva, 1000); 

}, 1000); 


But according to setInterval() is the best way in this case. While setInterval() calls the function "infinitely" always in the same time interval. And to pause the function, use clearInterval() . Passing the name of your range as a parameter.

var intervalo = window.setInterval(function() {

document.body.innerHTML += "."; 

}, 50);

window.setTimeout(function() {

    clearInterval(intervalo);

}, 3000);

jsbin - Sample clearInterval event running


If this image does not exist, it returns an error then ending the recursion.

MoshMage


Great, he wanted to demonstrate something by the OnError method, like this:

figura = document.createElement('img'); 

figura.onload = function() { 

document.body.appendChild(figura);
}
figura.onerror = function() {  

//display error

alert('Erro Fatal!')
}
figura.src = 'http://www.monkie.com.br/logo.png'; 

// Para prever tal comportamento na prática onError, 
// altere a url de destino retirando "logo.png"
// deixando-o http://www.monkie.com.br/ e teste novamente.

jsbin - Example of OnError event running


However this can be seen running the final result, check out:

const figura = document.createElement('img');

var diretorio = 'http://mplayer.xpg.uol.com.br/img/'

var numero = 0;

var intervalo = window.setInterval(visualizar, 1000)
function visualizar() {
figura.src = diretorio+numero+'.jpg'
document.getElementById("foto").appendChild(figura);
    numero++;
}

figura.onerror = function() 
{  
clearInterval(intervalo);
alert('Há '+numero+' fotos em '+diretorio);
} 
<span id="foto">&nbsp;</span>


Explanation snippet

Detail, if you know that the value of the figura variable will not change, the reserved statement const .

You can not call an anonymous function if it is not assigned to a variable. In case the anonymous function is assigned the variable figura preceded by "." followed by the onerror method, becoming accessible only when this variable is accessible, if the image does not exist, the browser interprets an error loading an image, triggered by the OnError method. This anonymous function uses clearInterval() which in turn is exactly that of allowing it to be passed as a parameter the name of its range, thus killing the continuous (recursive) process of the visualizar() function. Soon the event alert() is displayed, displaying the total of images loaded successfully, ie the exact amount of what is in the directory.


REMINDER - "All images must be named in ordinal numerals, otherwise impossible."


  

Finally, it was up to me to clarify in practice the theory given for each paragraph said by MoshMage.

    
23.01.2017 / 21:02