Skip to content

Instantly share code, notes, and snippets.

@darmentrout
Last active January 8, 2021 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darmentrout/b004fbebdfd1e7be4f7f6213ad99a9eb to your computer and use it in GitHub Desktop.
Save darmentrout/b004fbebdfd1e7be4f7f6213ad99a9eb to your computer and use it in GitHub Desktop.
A simple text editor for the browser
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Text Editor</title>
<style>
* { box-sizing: border-box; }
html,
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
body {
display: flex;
flex-direction: column;
height: 100vh;
}
header,
main {
padding: 1rem;
margin: 0;
}
header {
background-color: #eee;
border-bottom: 2px solid #666;
font-family: sans-serif;
}
h1 {
font-size: 2rem;
padding: 0;
margin: 0 0 1rem;
}
main {
font-family: monospace, sans-serif;
flex: 1;
}
footer {
background-color: #eee;
border-top: 2px solid #666;
margin: 0;
padding: 1rem;
}
</style>
</head>
<body>
<header>
<h1>Simple Text Editor</h1>
<a id="theFile" href="" download="default.txt" hidden="true"></a>
<label>
Load File:&nbsp;
<input id="fileInput" type="file">
</label>
<label>
File Name:&nbsp;
<input id="theFileName" value="text-file">
</label>
<button id="saveFile">Save</button>
</header>
<main id="theContent" contenteditable="true">Default text.</main>
<footer>&copy; <span id="copyright">MMXXI</span> Damion Armentrout</footer>
<script>
let theFile = document.getElementById('theFile');
let theFileName = document.getElementById('theFileName');
let theContent = document.getElementById('theContent');
const saveToFile = () => {
const theData = window.btoa(theContent.innerText);
theFile.href = 'data:text/plain;charset=utf-8;base64,' + theData;
theFile.download = theFileName.value + '.txt';
theFile.click();
}
document.getElementById('saveFile').addEventListener('click', saveToFile);
const theDate = new Date();
document.getElementById('copyright').innerText = theDate.getFullYear();
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
theContent.innerText = reader.result;
};
reader.onerror = function() {
theContent.innerText = reader.error;
};
}
let fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (e) => {
readFile(fileInput);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment