Allen Allen - 26 days ago 6
Javascript Question

Hide div when Save/Open box appears

I have a page with a list of mp3 urls. When you click on a specific item it fires off this javascript to download the mp3 file.

$(document).on('click', "a.item", function(e) {
var a_href = ($(this).closest('li').find('a.item').attr('href'));
e.preventDefault();
window.location.assign('download.php?q='+a_href);
});


this goes to a separate page (download.php) with this code:

$file= $_GET['q'];
header("Content-Type: audio/mp3");
header("Content-Disposition: attachment; filename=audio.mp3");
echo file_get_contents($file);


This works great and gives me the save or open dialog box. The problem is that the file may take a long time to get the contents, and so I can put a loading image up when the click occurs, but I need a way to identify when the save or open dialog box appears (so I can stop the loading image). Is there any way to do this?

Answer

Yes, most browsers fire the beforeunload event just before the Individual-file Download dialog opens.

So this would work:

$(window).bind ("beforeunload",  function (zEvent) {
    $("#dwnldStatus").text ("This code runs just before the file open/save dialog pops up.");
} );

$("#directDwnload").click ( function () {
    fireDownload ();
} );

$("#ResetTimer").click ( function () {
    $("#dwnldStatus").html (
        'Download will start in <span id="timeleft">3</span> seconds.'
    );
    fireTimer (3);
} );

function fireDownload () {
    window.location.assign (
        "http://download.thinkbroadband.com/5MB.zip"
    );
}

function fireTimer (secondsLeft) {
    this.secondsLeft    = secondsLeft || 30;
    this.countdownTimer = this.countdownTimer || null;

    if ( ! this.countdownTimer) {
        this.countdownTimer = setInterval ( function() {
                this.secondsLeft--;
                $("#timeleft").text (this.secondsLeft);
                if (this.secondsLeft <= 0) {
                    clearInterval (this.countdownTimer);
                    this.countdownTimer = null;
                    fireDownload ();
                }
            },
            1000
        );
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Activate one of the download buttons.  The timer button is just like any other javascript initiated download, no additional  click is needed.</p>
<p>The javascript detects when the File/Save dialog pops up and changes the status to "This code runs just before the file open/save dialog pops up.".</p>
<p>Note that it is not necessary to download the file. You can cancel the download.</p>

<div id="dwnldStatus"></div>
<button id="ResetTimer">Set timer to 3 seconds.</button>
<button id="directDwnload">Download the file now.</button>