JavaScript Example | Download a File

This javascript example code will show us how to download a file in javascript.

<!DOCTYPE html>
<html>

<head>
      <title>
            JavaScript Example | Download a File
      </title>
</head>

<body>

      <textarea id="text">NoteHope.com</textarea>
      <br />
      <input type="button" id="btn" value="Download" />
      <script>
            function download(filename, textInput) {

                  var element = document.createElement('a');
                  element.setAttribute('href','data:text/plain;charset=utf-8, ' + encodeURIComponent(textInput));
                  element.setAttribute('download', filename);
                  document.body.appendChild(element);
                  element.click();
                  //document.body.removeChild(element);
            }
            document.getElementById("btn")
                  .addEventListener("click", function () {
                        var text = document.getElementById("text").value;
                        var filename = "output.txt";
                        download(filename, text);
                  }, false);
      </script>
</body>

</html>