Reputation: 1183
I use an anchor tag to provide my users with an option to download some client side generated data in a file. I use the following code:
function GenerateTextFile (FileType, FileName, FileContents)
{
var data = new Blob ([FileContents], {type: 'text/plain'});
var url = window.URL.createObjectURL (data);
var link = document.createElement ("a");
link.download = FileName + "." + FileType ;
link.href = url ;
link.innerText = " Click here to download" ;
};
Later on I invoke the following to tidy up :
window.URL.revokeObjectURL (url);
Please can someone tell me how I can detect that the user has clicked on the anchor tag? I would like to either remove or change the text so that the download is not activated twice.
Upvotes: 0
Views: 531
Reputation: 6732
function GenerateTextFile(FileType, FileName, FileContents) {
var data = new Blob([FileContents], {
type: 'text/plain'
});
var url = window.URL.createObjectURL(data);
var link = document.createElement("a");
link.download = FileName + "." + FileType;
link.href = url;
link.innerText = " Click here to download";
link.id = Date.now();
link.setAttribute("onclick", "removeDownload('" + link.id + "')");
let links = document.getElementById("links");
links.appendChild(link);
};
function removeDownload(id) {
document.getElementById(id).remove();
}
<button onclick="GenerateTextFile('txt','test','lorem ipsum');">Create Dummy DL</button>
<div id="links"></div>
Note: The download of the file won't work within the snippet. It works outside of the sandbox though. This uses the onclick
event of the a
element with a dynamic id
(epoch) which then just calls the removeDownload
method, which will get the a element by its id
and remove it.
Upvotes: 1
Reputation: 2906
You can add a click listener to the link. Or is there some reason you don’t want that?
link.onclick = function(){console.log("link was clicked");}
Upvotes: 1