JSFiddle - React, Tailwind, and code Playground
HTML
<input id="input_id" data-filename="filename.txt" data-type="text/plain;charset=utf-8" />
<a data-download="input_id">Download</a>
CSS
a[data-download] {
text-decoration: none;
color: #FF8000;
cursor: pointer;
}
JavaScript
(function(){
var cleanup = null;
addEventListener("click",function(event){
if( cleanup )
cleanup();
for( var anchor = event.target; anchor && !(anchor instanceof HTMLAnchorElement); anchor=anchor.parentElement );
if( !anchor || !anchor.dataset.download ) return;
var source = document.getElementById( anchor.dataset.download );
if( !source ){
event.preventDefault();
return false;
}
var content = ("value" in source) ? source.value : ( source.textContent || source.innerText );
var options = {
type: source.dataset.type || "text/plain;charset=utf-8"
};
var blob = new Blob( [content], options );
var url = URL.createObjectURL( blob );
anchor.setAttribute( "download", source.dataset.filename || "" );
anchor.setAttribute( "href", url );
cleanup = function(){
anchor.removeAttribute("download");
anchor.removeAttribute("href");
URL.revokeObjectURL(url);
cleanup = null;
};
setTimeout(function(){
if(cleanup)
cleanup();
},1000);
});
})();