Question

I would like to style a Download Page with jquery.

The user enters a Link to a file from the Backend and the JS on the frontend does the rest. Thet means it gets the filesize via ajax. So I have something like this:

$(".downloads a").each(function() {
  var link = $(this);
  request = $.ajax({
    type: "HEAD",
    url: link.attr("href"),
    success: function() {
      var length = request.getResponseHeader("Content-Length");
      if (!isNaN(parseInt(length))) {
        var fileSize = readablizeBytes(length);
        var type = link.attr("href").split('.').pop();
        var text = link.html();
        link.html(text+'<span class="info">'+type+' - '+ fileSize  +'</span>');
      }
    }
  });
});

function readablizeBytes(bytes) {
  var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
  var e = Math.floor(Math.log(bytes)/Math.log(1024));
  return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
}

It works fine if I have only one Link. If I have two or more, only the last "a" get the "<span class="info">". Do you have an Idea how to fix this?

(All requests are executed, but the "link.html" functions only on the last "a")

Was it helpful?

Solution

What looks strange to me is that you use request = $.ajax() without var which means you override the next higher definition of request. If none is defined it will be in the global scope (window.request).

This could cause problems.

Rewrite it like:

$(".downloads a").each(function() {
  var link = $(this);
  $.ajax({
    type: "HEAD",
    url: link.attr("href"),
    success: function(data, textStatus, request) {
      var length = request.getResponseHeader("Content-Length");
      if (!isNaN(parseInt(length))) {
        var fileSize = readablizeBytes(length);
        var type = link.attr("href").split('.').pop();
        var text = link.html();
        link.html(text+'<span class="info">'+type+' - '+ fileSize  +'</span>');
      }
    }
  });
});

Although I can't reproduce your problem in any way.

OTHER TIPS

Change

var link = $(obj);

To

var link = $(this);

And try that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top