HTML5 Text Editor With File Reader API

HTML5 Text Editor With File Reader API
Code Snippet:HTML5 Text Editor
Author: Matt West
Published: January 18, 2024
Last Updated: January 22, 2024
Downloads: 276
License: MIT
Edit Code online: View on CodePen
Read More

This code creates an HTML5 text editor using File Reader APIs. It lets you create, edit, and delete text files. The text editor interface allows you to enter a filename, type content, and save it as a file. You can also browse existing files, load them for editing, and delete them if needed. The code manages file operations like saving, loading, and deleting within the browser using FileSystem API functionality.

You can use this code to build a simple text editor in a web browser. It’s handy for creating an interface to write, save, edit, and delete text files directly within the browser window. The major benefit is that it allows users to manage text files locally without needing an internet connection, handy for quick note-taking or local file management tasks.

How to Create HTML5 Text Editor With File Reader API

1. First of all, copy the following HTML code into your project. It includes the necessary structure for the text editor interface, such as the filename input, content textarea, save button, and file browser.

<div id="page-wrapper" class="clearfix">
    <h1>HTML5 Text Editor</h1>
    <p>Powered by the FileSystem APIs.</p>

    <form action="#" method="POST" id="file-form">
      <div class="field">
        <input type="text" name="filename" id="filename" placeholder="Filename (e.g. treehouse.txt)">
      </div>
      <div class="field">
        <textarea name="content" id="content" placeholder="Type your content here..."></textarea>
      </div>
      <div class="field">
        <button type="submit">Save File</button>
        <div id="messages"></div>
      </div>
    </form>

    <div id="files">
      <h2>File Browser</h2>
      <ul id="file-list"></ul>
    </div>

  </div>

2. The following CSS code enhances the visual appeal of the editor. Feel free to customize the styles to match your project’s design. The styles provide a clean and user-friendly interface for a seamless editing experience.

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
  color: #33383D;
  -webkit-font-smoothing: antialiased;
}

#page-wrapper {
  width: 960px;
  background: #FFF;
  padding: 1.25rem;
  margin: 1rem auto;
  min-height: 300px;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}

h1 {
  margin: 0;
}

h2 {
  margin-top: 0;
  font-size: 0.9rem;
  text-transform: uppercase;
  letter-spacing: 1px;
  color: #999;
}

p {
  font-size: 0.9rem;
  margin: 0.5rem 0 1.5rem 0;
}

a,
a:visited {
  color: #08C;
  text-decoration: none;
}

a:hover,
a:focus {
  color: #69c773;
  cursor: pointer;
}

a.delete-file,
a.delete-file:visited {
  color: #CC0000;
  margin-left: 0.5rem;
}

#file-form {
  width: 650px;
  float: left;
}

.field {
  margin-bottom: 1rem;
}

input,
textarea {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  border: 1px solid #D9D9D9;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
}

textarea {
  min-height: 300px;
}

button {
  display: inline-block;
  border-radius: 3px;
  border: none;
  font-size: 0.9rem;
  padding: 0.6rem 1em;
  background: #86b32d;
  border-bottom: 1px solid #5d7d1f;
  color: white;
  margin: 0 0.25rem;
  text-align: center;
}

button:hover {
  opacity: 0.75;
  cursor: pointer;
}

#files {
  width: 230px;
  float: right;
}

#files ul {
  margin: 0;
  padding: 0.5rem 1rem;
  height: 330px;
  overflow-y: auto;
  list-style: none;
  background: #F7F7F7;
  border: 1px solid #D9D9D9;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
}

#files li {
  padding: 0.5rem 0;
}

#messages {
  display: inline-block;
  font-weight: bold;
  color: #69c773;
  margin-left: 1rem;
}

/* Clearfix Utils */

.clearfix {
  *zoom: 1;
}

.clearfix:before,
.clearfix:after {
  display: table;
  line-height: 0;
  content: "";
}

.clearfix:after {
  clear: both;
}

3. The JavaScript code handles the core functionality of the text editor. It utilizes the File Reader API to manage file operations. The code includes functions for initializing the file system, loading files, saving files, and deleting files.

// Allow for vendor prefixes.
window.requestFileSystem = window.requestFileSystem ||
                           window.webkitRequestFileSystem;


// Create a variable that will store a reference to the FileSystem.
var filesystem = null;

// Get references to the page elements.
var form = document.getElementById('file-form');
var filenameInput = document.getElementById('filename');
var contentTextArea = document.getElementById('content');

var fileList = document.getElementById('file-list');

var messageBox = document.getElementById('messages');


// A simple error handler to be used throughout this demo.
function errorHandler(error) {
  var message = '';

  switch (error.code) {
    case FileError.SECURITY_ERR:
      message = 'Security Error';
      break;
    case FileError.NOT_FOUND_ERR:
      message = 'Not Found Error';
      break;
    case FileError.QUOTA_EXCEEDED_ERR:
      message = 'Quota Exceeded Error';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      message = 'Invalid Modification Error';
      break;
    case FileError.INVALID_STATE_ERR:
      message = 'Invalid State Error';
      break;
    default:
      message = 'Unknown Error';
      break;
  }

  console.log(message);
}


// Request a FileSystem and set the filesystem variable.
function initFileSystem() {
  navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5,
    function(grantedSize) {

      // Request a file system with the new size.
      window.requestFileSystem(window.PERSISTENT, grantedSize, function(fs) {

        // Set the filesystem variable.
        filesystem = fs;

        // Setup event listeners on the form.
        setupFormEventListener();

        // Update the file browser.
        listFiles();

      }, errorHandler);

    }, errorHandler);
}


function loadFile(filename) {
  filesystem.root.getFile(filename, {}, function(fileEntry) {

    fileEntry.file(function(file) {
      var reader = new FileReader();

      reader.onload = function(e) {
        // Update the form fields.
        filenameInput.value = filename;
        contentTextArea.value = this.result;
      };

      reader.readAsText(file);
    }, errorHandler);

  }, errorHandler);
}


function displayEntries(entries) {
  // Clear out the current file browser entries.
  fileList.innerHTML = '';

  entries.forEach(function(entry, i) {
    var li = document.createElement('li');

    var link = document.createElement('a');
    link.innerHTML = entry.name;
    link.className = 'edit-file';
    li.appendChild(link);

    var delLink = document.createElement('a');
    delLink.innerHTML = '[x]';
    delLink.className = 'delete-file';
    li.appendChild(delLink);

    fileList.appendChild(li);

    // Setup an event listener that will load the file when the link
    // is clicked.
    link.addEventListener('click', function(e) {
      e.preventDefault();
      loadFile(entry.name);
    });

    // Setup an event listener that will delete the file when the delete link
    // is clicked.
    delLink.addEventListener('click', function(e) {
      e.preventDefault();
      deleteFile(entry.name);
    });
  });
}


function listFiles() {
  var dirReader = filesystem.root.createReader();
  var entries = [];

  var fetchEntries = function() {
    dirReader.readEntries(function(results) {
      if (!results.length) {
        displayEntries(entries.sort().reverse());
      } else {
        entries = entries.concat(results);
        fetchEntries();
      }
    }, errorHandler);
  };

  fetchEntries();
}


// Save a file in the FileSystem.
function saveFile(filename, content) {
  filesystem.root.getFile(filename, {create: true}, function(fileEntry) {

    fileEntry.createWriter(function(fileWriter) {

      fileWriter.onwriteend = function(e) {
        // Update the file browser.
        listFiles();

        // Clean out the form field.
        filenameInput.value = '';
        contentTextArea.value = '';

        // Show a saved message.
        messageBox.innerHTML = 'File saved!';
      };

      fileWriter.onerror = function(e) {
        console.log('Write error: ' + e.toString());
        alert('An error occurred and your file could not be saved!');
      };

      var contentBlob = new Blob([content], {type: 'text/plain'});

      fileWriter.write(contentBlob);

    }, errorHandler);

  }, errorHandler);
}


function deleteFile(filename) {
  filesystem.root.getFile(filename, {create: false}, function(fileEntry) {

    fileEntry.remove(function(e) {
      // Update the file browser.
      listFiles();

      // Show a deleted message.
      messageBox.innerHTML = 'File deleted!';
    }, errorHandler);

  }, errorHandler);
}


// Add event listeners on the form.
function setupFormEventListener() {

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    // Get the form data.
    var filename = filenameInput.value;
    var content = contentTextArea.value;

    // Save the file.
    saveFile(filename, content);
  });

}

// Start the app by requesting a FileSystem (if the browser supports the API)
if (window.requestFileSystem) {
  initFileSystem();
} else {
  alert('Sorry! Your browser doesnt support the FileSystem API :(');
}

Feel free to customize the code to suit your needs. You can add additional features, improve the user interface, or integrate it into a larger web application.

That’s all! hopefully, you have successfully created Html5 Text Editor With File Reader API. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X