JavaScript to Confirm a File Download CodeUnit 27 JAN 2011

A confirmation dialogue is handy when you want to make sure that the selected action is actually meant to take place and isn’t just the result of an accidental click. Of course, achieving this is super easy thanks to JavaScript’s built in dialog box functions, the one we are most interested in this case being ‘confirm’.

So let’s look at this in code then:

var confirmed = confirm('Do you wish to download this PDF file?');
if (confirmed){
	window.open('/pdfs/download.pdf');
} else {
	alert('download cancelled');
}

Of course, you wouldn’t normally bother with the else part of the statement, though it is useful to show when you start thinking of building more complex decisions based on a combination of confirms and cancels.

Nifty.

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.