Martin Tomko Martin Tomko - 4 months ago 16
Javascript Question

JQuery AJAX Read files from folder backwards

i am using this code for website to load all images from folder into page. But as u can see i am using prepend command because images are named like "0001","0002","0003" so script first reads 0001 file and i need to show latest number first.

Is there way to read name of files backward?
(first 0003 then 0002, 0001..)

Code i am using now (i found this code there on stackoverflow):

var dir = "img/Torty/";
var fileextension = ".jpg";
$.ajax({
url: dir
, success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
if (filename.indexOf("+s+") >= 0) {
var splitted = filename.split("+");
$("#tortySem").prepend("<p><img src='" + dir + filename + "'></p>");
$("#tortySem").prepend("<p>Torta " + parseInt(splitted[0]) + " Váha " + splitted[1] + "Kg</p>");
}
});
}
});

Answer

Try using .toArray(), Array.prototype.reverse(), .append()

$($(data).find("a:contains(" + fileextension + ")").toArray().reverse())
.each(function () {
  var filename = this.href.replace(window.location.host, "")
                 .replace("http:///", "");
  if (filename.indexOf("+s+") >= 0) {
    var splitted = filename.split("+");
    $("#tortySem")
    .append("<p><img src='" + dir + filename + "'></p>");
    $("#tortySem")
    .append("<p>Torta " 
      + parseInt(splitted[0]) 
      + "   Váha " 
      + splitted[1] 
      + "Kg</p>");
  }
});

var data = "<div><a href=0001>0001</a><a href=0002>0002</a><a href=0003>0003</a></div>";

var n = "000";

$($(data).find("a:contains(" + n + ")").toArray().reverse())
.each(function() {
  $("div").append(this, "<br>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Comments