Last active
January 8, 2021 17:53
-
-
Save darmentrout/b004fbebdfd1e7be4f7f6213ad99a9eb to your computer and use it in GitHub Desktop.
A simple text editor for the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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: | |
<input id="fileInput" type="file"> | |
</label> | |
<label> | |
File Name: | |
<input id="theFileName" value="text-file"> | |
</label> | |
<button id="saveFile">Save</button> | |
</header> | |
<main id="theContent" contenteditable="true">Default text.</main> | |
<footer>© <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