Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active July 12, 2020 08:41
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 miguelmota/caed0b56078bc02b3a4d57e04e5d22ea to your computer and use it in GitHub Desktop.
Save miguelmota/caed0b56078bc02b3a4d57e04e5d22ea to your computer and use it in GitHub Desktop.
JavaScript base64 encoder and decoder example
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=yes">
<title>Base64 Encoder/Decoder</title>
<style>
form {
display: block;
margin-bottom: 2em;
}
label {
display: block;
margin-bottom: 0.5em;
}
input {
width: 100%;
margin-bottom: 0.5em;
}
button {
margin-bottom: 0.5em;
}
</style>
</head>
<body>
<h1>Base64 encode or decode</h1>
<form id="encodeForm">
<label>Text to base64 encode</label>
<div>
<input type="text" placeholder="text" id="encodeText" />
</div>
<button type="submit">Encode</button>
<div id="encodedOutput"></div>
</form>
<form id="decodeForm">
<label>base64 encoded text to decode</label>
<div>
<input type="text" placeholder="base64" id="decodeText" />
</div>
<button type="submit">Decode</button>
<div id="decodedOutput"></div>
</form>
<script>
const encodeForm = document.querySelector('#encodeForm')
const decodeForm = document.querySelector('#decodeForm')
const encodeText = document.querySelector('#encodeText')
const decodeText = document.querySelector('#decodeText')
const encodedOuput = document.querySelector('#encodedOutput')
const decodedOutput = document.querySelector('#decodedOutput')
encodeForm.addEventListener('submit', function(event) {
event.preventDefault()
encodedOutput.textContent = btoa(encodeText.value)
})
decodeForm.addEventListener('submit', function(event) {
event.preventDefault()
decodedOutput.textContent = atob(decodeText.value)
})
</script>
<a href="https://gist.github.com/miguelmota/caed0b56078bc02b3a4d57e04e5d22ea" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment