Coding Triumph

Helpful code snippets & tutorials

How to download textarea’s content as a file with JavaScript

In this post, I’ll be showing you how you can download a textarea’s content, or any input field for that matter, as a text file using only JavaScript. There is no need for any complicated library or a backend server.

1. The HTML:

This is a minimal working HTML markup. Of course, real-world examples can be more complicated.

<textarea></textarea>
<button>Download</button>

2. Download textarea content with vanilla JavaScript:

We’ll be using the Blob object and the download attribute, which are both supported by all modern browsers. And here is the script with detailed comments:

const textarea = document.querySelector('textarea');
const btn = document.querySelector('button');

btn.addEventListener('click', () => {
  // get the text from the textarea
  const text = textarea.value.trim();

  // if the text is empty, do nothing
  if (text === '') return;

  // create a new Blob object with the text data and the appropriate mime-type
  const blob = new Blob([text], { type: 'plain/text' });

  // create a DOMString containing a URL representing the Blob object
  const url = URL.createObjectURL(blob);

  // create a temporary anchor element
  const anchor = document.createElement('a');
  anchor.setAttribute('href', url);
  anchor.setAttribute('download', 'result.txt'); // set the file name
  anchor.style.display = 'none';

  // add the new anchor to the DOM and trigger a click event
  document.body.appendChild(anchor);
  anchor.click();

  // finally remove the anchor from the DOM
  document.body.removeChild(anchor);
});

2. Download textarea content with vanilla jQuery:

If, on the other hand, you prefer to use jQuery, this is the same script adapted for your use case.

$('button').on('click', function () {
  const text = $('textarea').val().trim();

  // get the text from the textarea
  if (text === '') return;

  // create a new Blob object with the text data and the appropriate mime-type
  const blob = new Blob([text], { type: 'plain/text' });

  // create a DOMString containing a URL representing the Blob object
  const url = URL.createObjectURL(blob);

  // create a temporary anchor element
  const $anchor = $('<a></a>')
    .attr('href', url)
    .attr('download', 'result.txt')
    .hide();

  // add the new anchor to the DOM
  $('body').append($anchor);

  /**
   * Trigger native click event on the anchor element
   *
   * For cross-browser consistency, disables native click events from links
   * To trigger the native click event, we need the DOM node (get(0))
   */
  $anchor.get(0).click();

  // remove the anchor from the DOM
  $('body').remove($anchor);
});

That’s all guys. Have a nice day!

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments