Search code examples
javascriptjquerydownloadmp3

DIV Click Download Audio File


I have this audio MP3 file and I want to have it downloaded when the user clicks a DIV using JavaScript/JQuery.

$("#button").live("click",function(){
    // initiate download
});

Any help whatsoever would be appreciated. I can't seem to find anything on this topic. Thanks!


Solution

  • The iframe answer is one way to do it, but often times the MP3 will simply play inside the iframe, so if you don't want to bother with any server side work, and the MP3s are hosted by you (at least in Firefox, this isn't required in Chrome), you can use the download attribute of the a element.

    <a href="audio.MP3" download="DownloadedFilenameHere.mp3">Download</a>
    

    If you really need it to be a DIV, you can either encase the div in the a element or use a Javascript workaround like this one. One nice advantage to a JS solution is you can do this for multiple files at once.

    var link = document.createElement('a');
    link.href = "audio.MP3";
    link.setAttribute('download', "DownloadedFilenameHere.mp3");
    document.getElementsByTagName("body")[0].appendChild(link);
    // Firefox
    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initEvent("click", true, true);
        link.dispatchEvent(event);
    }
    // IE
    else if (link.click) {
        link.click();
    }
    link.parentNode.removeChild(link);
    

    If you want this for multiple downloads, just use window.setInterval and use an interval of 500 milliseconds. Using a for loop won't work because for one reason or another Firefox isn't able to handle that many downloads at once, and you must space it out instead.