Skip to content

Instantly share code, notes, and snippets.

@fstorr
Last active December 16, 2015 21:09
Show Gist options
  • Save fstorr/5497272 to your computer and use it in GitHub Desktop.
Save fstorr/5497272 to your computer and use it in GitHub Desktop.
Setting the HTML5 download attribute in capable browser. This assumes support for document.querySelector.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML download attribute</title>
</head>
<body>
<ul>
<li><a href="downloadable-file.txt">View your invoice</a></li>
<li class="download"><a href="downloadable-file.txt">Right-click and select Save to download your invoice</a></li>
</ul>
<script>
var DlLink = document.querySelector(".download a");
if('download' in document.createElement('a')){
DlLink.setAttribute("download", "invoice-may-2013.txt");
DlLink.innerHTML = "Save your invoice";
}
// else{
// DlLink.addEventListener("click", function(e){e.preventDefault()}, false); // prevent the link being followed. Might not be the best idea
// }
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment