0

Can someone explain to me how this piece of code works. Also, the output is not what I want. It saves 2 files instead of 1.
Javascript

function saveTextAsFile() {
     var textToWrite = document.getElementById('textArea').innerHTML;
     var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
     var fileNameToSaveAs = "file.txt";
   
     var downloadLink = document.createElement("a");
     downloadLink.download = fileNameToSaveAs;
     downloadLink.innerHTML = "Download File";
     if (window.webkitURL != null) {
       downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
     } else {
       downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
       downloadLink.onclick = destroyClickedElement;
       downloadLink.style.display = "none";
       document.body.appendChild(downloadLink);
     }
   
     downloadLink.click();
   }
   
   var button = document.getElementById('save');
   button.addEventListener('click', saveTextAsFile);
   
   function destroyClickedElement(event) {
     document.body.removeChild(event.target);
   }

HTML

    <button id="save" onclick="saveTextAsFile()">Save</button>
    <textarea id="textArea" class="Textarea" placeholder="Click to Type" cols="20"></textarea>

1 Answer 1

2

You code does NOT work:

  1. textarea input values are read with .value not .innerHTML, you where getting no output so change: var textToWrite = document.getElementById('textArea').innerHTML; into var textToWrite = document.getElementById('textArea').value;

  2. You get 2 files because you made 2 same events on same button that call same function, remove one of those:

    <button id="save" onclick="saveTextAsFile()">Save</button> here remove onclick="saveTextAsFile()" or remove this two lines:

    var button = document.getElementById('save');

    button.addEventListener('click', saveTextAsFile);

This will fix your errors, and as far how whole code works, this is not code review site, for that visit https://codereview.stackexchange.com/ or google each command and read its definitions.

Sign up to request clarification or add additional context in comments.

2 Comments

When I tried removing var button = document.getElementById('save'); button.addEventListener('click', saveTextAsFile);it still saved 2 files. But other than that, when I tried removing onclick="saveTextAsFile()" it worked fine. Thanks
@SomeRandomUser101_ Not possible with code you presented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.