JSFiddle - React, Tailwind, and code Playground
by ysuper
HTML
<html>
<body>
<style>
p {
color: green;
}
</style>
<p>How to trigger a file download when clicking an HTML button or JavaScript?
<p>
<textarea id="text">Welcome to GeeksforGeeks</textarea>
<br/>
<input type="button" id="btn" value="Download" />
<script>
function download(file, text) {
//creating an invisible element
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8, '
+ encodeURIComponent(text));
element.setAttribute('download', file);
//the above code is equivalent to
// <a href="path of file" download="file name">
document.body.appendChild(element);
//onClick property
element.click();
document.body.removeChild(element);
}
// Start file download.
document.getElementById("btn").addEventListener("click", function() {
// Generate download of hello.txt file with some content
var text = document.getElementById("text").value;
var filename = "GFG.txt";
download(filename, text);
}, false);
</script>
</body>
</html>