Have a Snippet?

Keep, track and share your code snippets with your friends

jQuery: Display file sizes next to download links Share on Vkontakte

«jQuery Trickshots» by tutorialzine.com

// Loop all .fetchSize links
$('a.fetchSize').each(function(){
 
  // Issue an AJAX HEAD request for each one
    var link = this;
 
    $.ajax({
        type: 'HEAD',
        url: link.href,
        complete: function(xhr){
            var size = humanize(xhr.getResponseHeader('Content-Length'));
 
            // Append the filesize to each
            $(link).append(' (' + type + ')');
        }
    });
});
 
function humanize(size){
    var units = ['bytes','KB','MB','GB','TB','PB'];
 
    var ord = Math.floor( Math.log(size) / Math.log(1024) );
    ord = Math.min( Math.max(0,ord), units.length-1);
 
    var s = Math.round((size / Math.pow(1024,ord))*100)/100;
    return s + ' ' + units[ord];
}
 
// html
// First Trickshot
// This Trickshot
// Ball.png


Tag: jQuery, JavaScript, Ajax

0 Comments