I'm trying to make a dark mode toggle button which can toggle between dark and light mode on click, User preference is also stored using localStorage. The user should manually press the button to toggle to other mode. If the user's choice is dark mode, Every page will be in dark mode and it doesn't turn to light mode on refreshing. Everything looks fine upto now but the real issue comes with loading time. The load time of a page is nearly 1 second and in that time, Page appears to be in light mode even if user's choice is dark mode. I don't want that to happen. I want loading time section in dark mode if user's choice is dark.
This is my current code:
<script>
const body = document.querySelector('body');
function toggleDark() {
if (body.classList.contains('dark')) {
body.classList.remove('dark');
localStorage.setItem("theme", "light");
} else {
body.classList.add('dark');
localStorage.setItem("theme", "dark");
}
}
if (localStorage.getItem("theme") === "dark") {
body.classList.add('dark');
}
</script>
<style>
body {background-color: #ffffff}
body.dark {background-color: #000000; color: #ffffff}
</style>
<button class="dark-mode" id="btn-id" onclick="toggleDark()"></button>
Another alternative is to load the script in the <head> element, and toggle the class on html element
To do so, you use document.documentElement.classList as that is the HTML element
Then change your CSS to
html.dark body {}
etc .. the class selector on HTML
html body {background-color: #ffffff}
html.dark body {background-color: #000000; color: #ffffff}
<script>
const body = document.querySelector('body');
function toggleDark() {
if (document.documentElement.classList.contains('dark')) {
document.documentElement.classList.remove('dark');
//localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add('dark');
//localStorage.setItem("theme", "dark");
}
}
//if (localStorage.getItem("theme") === "dark") {
document.documentElement.classList.add('dark');
//}
</script>
<button class="dark-mode" id="btn-id" onclick="toggleDark()">DARK</button>
Due to restrictions, localStorage is unavailable on stack overflow - uncomment those lines to see it work
Or - see https://jsfiddle.net/e9zg2p4c/
Store it to backend database. Then when serving HTML content put proper class/style for your elements. This will remove flickering between loading times:
<!DOCTYPE html>
<html>
<head>
<style>
/* Use Less/Sass for better management */
.theme.light {
background-color: #ffffff;
}
.theme.dark {
background-color: #000000; color: #ffffff;
}
</style>
</head>
<body class="theme <?= $user->themeName; ?>">
</body>
</html>
A little more tricky to toggle AND have a default theme
Note the localStorage calls do not work here at SO
working example
In the code below replace
const theme = "dark"; with
localStorage.getItem("theme") || "light"
and uncomment // localStorage.setItem("theme", body.classList.contains("dark") ? "light" : "dark");
on your server
.dark { background-color: black; color: white; }
<!DOCTYPE html>
<html>
<head>
<style>
.theme {
background-color: white;
color: black;
}
</style>
<script>
const theme = "dark"; // localStorage.getItem("theme") || "theme"
if (theme === "dark") {
const st = document.createElement("style");
st.id="darkStyle";
st.innerText = `body.theme { background-color: black; color: white; }`;
document.querySelector("head").appendChild(st);
}
window.addEventListener("load", function() {
document.getElementById("toggleTheme").addEventListener("click", function() {
const body = document.querySelector("body");
const darkStyle = document.getElementById("darkStyle");
if (darkStyle) {
darkStyle.remove(); // remove stylesheet now we know what the user wants
body.classList.remove("theme");
}
const theme = body.classList.contains("theme");
body.classList.toggle('theme',!theme);
body.classList.toggle('dark',theme);
// localStorage.setItem("theme", theme ? "light" : "dark"); // uncomment on your server
});
})
</script>
</head>
<body class="theme">
Here is the body
<button id="toggleTheme" type="button">Toggle theme</button>
</body>
</html>
Given that the only real difference between light and dark is the colours, why not simply create css variables for each colour you are going to use and use javascript to change the values of the variables. This way, once you have defined the classes using the variables in the appropriate places, changing the variable values changes the classes automatically. The choice of "dark" and "light" can be stored in whatever way is available to you - localStorage, cookies or backend etc - and you simply set the appropriate colours to the css variables when the page is being loaded. There's no need for separate definitions for each class and, as a developer, it allows you to quickly test the colour schemes without having to manually change every class one by one.
function changeTheme(t) {
if (t == "dark") {
document.documentElement.style.setProperty("--backgroundcolour", "black");
document.documentElement.style.setProperty("--fontcolour", "white");
} else {
document.documentElement.style.setProperty("--backgroundcolour", "white");
document.documentElement.style.setProperty("--fontcolour", "black");
}
}
:root {
--backgroundcolour:black;
--fontcolour:white;
}
body {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
span {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
div {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
table {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
<button onclick="changeTheme('dark');">Use dark theme</button><button onclick="changeTheme('light');">Use light theme</button>
<hr>
<span>Text in a span</span>
<hr>
<div>Text in a div</div>
<hr>
<table>
<tbody>
<tr><td>Text in a table</td></tr>
</tbody>
</table>
If you want to use checkbox, this solution for you.
if you want the value to remain unchanged, use localStorage. If you want a dark mode where you have values disappear when you close a tab or browser, use sessionStorage.
const check = document.getElementById('chk');
check.addEventListener('change', () => {
document.body.classList.toggle('dark');
localStorage.darkMode=!localStorage.darkMode;
});
window.onload=function() {
if(localStorage.darkMode) document.body.classList.toggle('dark');
}
#modeSwitcher{
margin: 5% 50%;
}
#modeSwitcher .checkbox {
opacity: 0;
position: absolute;
}
#modeSwitcher .checkbox:checked + .label .ball{
transform: translateX(35px);
}
#modeSwitcher .checkbox:checked + .label .ball::after{
content: '';
position: absolute;
background-color: #0A0E27;
width: 13px;
height: 13px;
border-radius: 50%;
bottom: 50%;
left: -5%;
transform: translateY(50%);
}
#modeSwitcher .label {
background-color: #0A0E27;
border-radius: 50px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px;
margin: 0;
position: relative;
height: 16px;
width: 50px;
transform: scale(1.5);
}
#modeSwitcher .label .fa-moon{
color:#0A0E27 ;
}
#modeSwitcher .label .ball {
background-color: #FDC503;
border-radius: 50%;
position: absolute;
top: 3px;
left: 3px;
height: 20px;
width: 20px;
transform: translateX(0px);
transition: transform 0.2s linear;
}
body{
background-color: #fff;
}
body.dark{
background-color: black;
}
<div id="modeSwitcher">
<input type="checkbox" class="checkbox" id="chk" />
<label class="label" for="chk">
<i class="fas fa-moon"></i>
<div class="ball"></div>
</label>
</div>
Related
I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.
Desired behavior:
I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.
I have done a little test of loading it by JS with the following code (which works).
GREEN
<head>
...
<link rel="stylesheet" href="/assets/css/{{'light'}}.css">
...
</head>
This loads the CSS file called "light" as expected.
But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:
RED
<head>
...
<script>
var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
</script>
<link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
...
</head>
Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.
After that I thought that maybe creating an element would do the trick and I created one manually to test it:
RED
<head>
...
<p id="theme" style="display:none;">dark</p>
<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
And nope, the path still appears as: /assets/css/.css
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main> and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.
The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:
Click the green Preview button.
Another frame should appear on the right. Within the frame is the webpage example click the ☀️ button.
It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.
The page should still be in dark mode. 👍
/* night.css
main {
background: #000;
color: #fff;
}
*/
/* default.css */
:root {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font: 1ch/1.5 'Segoe UI';
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-size: 4ch;
}
main {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
color: #000;
}
form {
width: 80vw;
margin: 20px auto;
}
fieldset {
width: max-content;
min-height: 25px;
margin-left: auto;
padding: 0 1.5px 1.5px;
border-radius: 8px;
background: inherit;
color: inherit;
}
button {
display: block;
width: 100%;
height: 100%;
border: 0;
font-size: 4rem;
text-align: center;
background: transparent;
cursor: pointer;
}
#theme::before {
content: '☀️';
}
.night #theme::before {
content: '🌙';
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='lib/default.css' rel='stylesheet'>
<link class='night' href='lib/night.css' rel='stylesheet' disabled>
<style></style>
</head>
<body>
<main>
<form id='UI'>
<fieldset name='box'>
<legend>Theme</legend>
<button id='theme' type='button'></button>
</fieldset>
<p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
<link>`s.</p>
</form>
</main>
<script>
const UI = document.forms.UI;
const M = document.querySelector('main');
const L = document.querySelector('.night')
const switchTheme = e => {
const clk = e.target;
if (clk.matches('button')) {
M.classList.toggle('night');
L.toggleAttribute('disabled');
}
let status = M.className === 'night' ? 'on' : 'off';
localStorage.setItem('theme', status);
};
const loadTheme = e => {
let cfg = localStorage.getItem('theme');
if (cfg === 'on') {
M.classList.add('night');
L.removeAttribute('disabled');
} else {
M.classList.remove('night');
L.setAttribute('disabled', true);
}
};
UI.addEventListener('click', switchTheme);
document.addEventListener('DOMContentLoaded', loadTheme);
</script>
</body>
</html>
This is my code. Im new to JavaScript so idk what I'm really doing. Basically, every time the button is clicked, a new Van Gogh detail/image should fill the background. I feel like many images are repeated and sometimes the button doesn't work (a new image doesn't appear on each click). Ideally, I would like a new image with each click. For now, I only have 10 images, but may add more. Thank you for your help.
HTML
<!DOCTYPE html>
<html>
<head>
<title>VG java project</title>
<link rel="stylesheet" type="text/css" href="assets/main.css">
<script src="assets/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="assets/main.js"></script>
</head>
<body>
<div class="container1"></div>
<div class="container">
<div class="button">
Do you like Van Gogh?
</div>
</div>
</body>
</html>
CSS
body {
font-family: courier new;
padding: 3rem;
z-index: 200;
background: url(gogh4.jpg);
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.item {
max-width: 960px;
text-align: center;
}
.button {
position: absolute;
left: 50px;
top: 50px;
border: 7px double;
border-color: black;
padding: 20px;
font-size: 40px;
background-color: rgb(225, 186, 253);
opacity: 80%;
}
.button:hover {
background-color: rgb(197, 103, 247);
color: white;
cursor: pointer;
opacity: 90%;
}
.gogh1 {
background: url(gogh1.jpg);
}
.gogh2 {
background: url(gogh3.jpg);
}
.gogh3 {
background: url(gogh3.jpg);
}
.gogh4 {
background: url(gogh4.jpg);
}
.gogh5 {
background: url(gogh5.jpg);
}
.gogh6 {
background: url(gogh6.jpg);
}
.gogh7 {
background: url(gogh7.jpg);
}
.gogh8 {
background: url(gogh8.jpg);
}
.gogh9 {
background: url(gogh9.jpg);
}
.gogh10 {
background: url(gogh10.jpg);
}
.highlight {
font-size: 200px;
}
JavaScript ~ I'm using jQuery btw
$(function() {
$(".button").click(function(){
let goghs = ["gogh1", "gogh2", "gogh3", "gogh4",
"gogh5", "gogh6", "gogh7", "gogh8",
"gogh9", "gogh10"]
let i = Math.floor(Math.random()* goghs.length - Math.random() + 2 );
$("body").toggleClass(goghs[i]);
});
});
Since You asked for Javascript help.
Here's a problem you had in your code:
Edited:
$(function () {
$(".button").click(function () {
let goghs = ["gogh1", "gogh2", "gogh3", "gogh4",
"gogh5", "gogh6", "gogh7", "gogh8",
"gogh9", "gogh10"
]
let i = Math.floor(Math.random() * goghs.length); //There was no need to add + Random plus 2 to it. You already Selecting a random index from an array(sometimes 'i' value was 10 -> undefined).
console.log(i, goghs[i]); //logging helps you notice that is nothing wrong with other parts and function runs. only the code itself has some problems.
$("body").toggleClass(goghs[i]);
});
});
If "i" is 2 the first time around then "gogh2" get added as the class.
If "i" is 3 the second time around the "gogh3" will be 'added' to the class list. "gogh2" will still be there.
Then, if "i" is 2 the third time around, then it will remove "gogh2" and you'll just be left with "gogh3".
Try:
$("body").removeClass();
$("body").addClass(goghs[i]);
and do away with your toggleClass line.
toggleClass will add the class to the list if it's not there and remove it if it is.
I have been trying to find out how to call my function that is inside a function that is started on page load to set darkmode.
If anyone could help me with this I would be very grateful.
Here is my js file:
(function() {
var darkSwitch = document.getElementById("darkSwitch");
if (darkSwitch) {
initTheme();
darkSwitch.addEventListener("change", function(event) {
resetTheme();
});
function initTheme() {
var darkThemeSelected =
localStorage.getItem("darkSwitch") !== null &&
localStorage.getItem("darkSwitch") === "dark";
darkSwitch.checked = darkThemeSelected;
darkThemeSelected
? document.body.setAttribute("data-theme", "dark")
: document.body.removeAttribute("data-theme");
}
function resetTheme() {
if (darkSwitch.checked) {
document.body.setAttribute("data-theme", "dark");
localStorage.setItem("darkSwitch", "dark");
} else {
document.body.removeAttribute("data-theme");
localStorage.removeItem("darkSwitch");
}
}
}
})();
The js file comes from this GitHub:
https://github.com/coliff/dark-mode-switch
I think you try when the page is load is in dark mode.
here is the solution of your problem.
Here its Documentation :
Here's a link! This code is from Codepen.
HTML:
<script>
// Include this script near the top of your html
var app = document.getElementsByTagName("BODY")[0];
if (localStorage.lightMode == "dark") {
app.setAttribute("data-light-mode", "dark");
}
</script>
<h1>
Dark Mode Toggle
</h1>
<p>Uses localStorage to store and apply the set light mode when page is loaded</p>
<button onclick="toggle_light_mode()">
Toggle Light Mode
</button>
CSS
body {
transition: background-color 0.3s;
text-align: center;
font-family: sans-serif;
padding-top: 3em;
}
h1 {
font-weight: normal;
}
button {
padding: 1em;
font-size: 1em;
background: #000;
color: #fff;
border: none;
cursor: pointer;
transition: .3s;
}
button:hover {
opacity:.5;
}
body[data-light-mode="dark"] {
background-color: #000;
color: #eee;
}
body[data-light-mode="dark"] button {
background-color: #fff;
color: #000;
}
JS
function toggle_light_mode() {
var app = document.getElementsByTagName("BODY")[0];
if (localStorage.lightMode == "dark") {
localStorage.lightMode = "light";
app.setAttribute("data-light-mode", "light");
} else {
localStorage.lightMode = "dark";
app.setAttribute("data-light-mode", "dark");
}
console.log("lightMode = " + localStorage.lightMode);
}
I've been trying to implement persistent dark mode on web pages, as when a user navigates through pages, their choice will be remembered. Also, I added a toggle dark/light mode button, for better user experience. Thus I came up with this code:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#002f30">
<style>
body {
padding: 25px;
color: black;
font-size: 25px;
}
.btn {
background: white;
border: 1px solid #10101c;
color: #10101c;
border-radius:0.5rem;
}
a {
text-decoration: none;
color: #006262;
border-bottom: 1px dotted #192841;
font-style: italic;
}
body.dark {
background-color: #10101c;
color: #778899;
}
body.dark .btn {
background: #10101c;
color: #708090;
border: 1px solid #002e43;
border-radius:0.5rem;
}
body.dark a {
text-decoration: none;
color: #778899;
border-bottom: 1px dotted #d5c4a1;
font-style: italic;
}
</style>
</head>
<body>
<h1 style="margin-top: 0">page 1</h1>
<h2 style="margin-top: 0">Toggle Dark/Light Mode</h2>
<p>Click the button to toggle between dark and light mode for this page.</p>
<p>This is a link to a second page click</p>
<button id="mode" class="btn" onclick="toggle()">Toggle dark mode</button>
<script>
function toggle() {
// This bit is for the toggling between dark and light mode
let element = document.body;
element.classList.toggle("dark");
// This part is for toggling the text inside the button
var toggle = document.getElementById("mode");
if (toggle.innerHTML === "Toggle dark mode") {
toggle.innerHTML = "Dark mode it is";
}
else {
toggle.innerHTML = "Toggle dark mode"; }
// This part I copy pasted from one of Kevin Powell's videos on darkmode switch, and maintaining persistence but still couldn't figure out howbit works...
// check for saved 'darkMode' in localStorage
let darkMode = localStorage.getItem('darkMode');
const darkModeToggle = document.querySelector('#mode');
const enableDarkMode = () => {
// 1. Add the class to the body
document.body.classList.add('dark');
// 2. Update darkMode in localStorage
localStorage.setItem('darkMode', 'enabled');
}
const disableDarkMode = () => {
// 1. Remove the class from the body
document.body.classList.remove('dark');
// 2. Update darkMode in localStorage
localStorage.setItem('darkMode', null);
}
// If the user already visited and enabled darkMode
// start things off with it on
if (darkMode === 'enabled') {
enableDarkMode();
}
// When someone clicks the button
darkModeToggle.addEventListener('click', () => {
// get their darkMode setting
darkMode = localStorage.getItem('darkMode');
// if it not current enabled, enable it
if (darkMode !== 'enabled') {
enableDarkMode();
// if it has been enabled, turn it off
} else {
disableDarkMode();
}
});
// This is the solved part I asked earlier, it chages the meta theme color with the dark or light mode change
var meta = document.querySelector("meta[name=theme-color]");
if (meta.getAttribute("content") === "#002f30") {
console.log(meta.getAttribute("content"));
meta.setAttribute("content", "#10101c");
} else {
console.log(meta.getAttribute("content"));
meta.setAttribute("content", "#002f30");
}
}
</script>
</body>
</html>
While running the code, everything works fine except for the persistence part. If dark mode is enabled, and I navigate to a second page of the same html code, it turns back to default light mode. Am I doing the code right?
P.S. I'm a novice/beginner in Javascript
// Using a local variable since stack overflow doesn't allow localstorage operations for security purposes.
let storage = {darkMode: "disabled"}
function userPreferesDarkMode() {
//return localStorage.getItem("darkMode") === "enabled";
return storage.darkMode === "enabled";
}
function setThemePreference(value) {
// localStorage.setItem("darkMode", value || "disabled");
storage.darkMode = value || "disabled";
}
const enableDarkMode = () => {
// 1. Add the class to the body
document.body.classList.add("dark");
};
const disableDarkMode = () => {
// 1. Remove the class from the body
document.body.classList.remove("dark");
};
function setTheme() {
// If the user already visited and enabled darkMode
// start things off with it on
if (userPreferesDarkMode()) {
enableDarkMode();
} else {
disableDarkMode();
}
const appDiv = document.getElementById("app");
appDiv.innerHTML = `<h1>Dark mode: ${userPreferesDarkMode()}</h1>`;
}
function bootstrap() {
const darkModeToggleButton = document.querySelector("#mode");
darkModeToggleButton.addEventListener("click", () => {
if (userPreferesDarkMode()) {
setThemePreference("disabled");
disableDarkMode();
} else {
setThemePreference("enabled");
enableDarkMode();
}
const appDiv = document.getElementById("app");
appDiv.innerHTML = `<h1>Dark mode: ${userPreferesDarkMode()}</h1>`;
});
setTheme();
}
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
bootstrap()
});
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
<style>
body {
padding: 25px;
color: black;
font-size: 25px;
}
.btn {
background: white;
border: 1px solid #10101c;
color: #10101c;
border-radius:0.5rem;
}
a {
text-decoration: none;
color: #006262;
border-bottom: 1px dotted #192841;
font-style: italic;
}
body.dark {
background-color: #10101c;
color: #778899;
}
body.dark .btn {
background: #10101c;
color: #708090;
border: 1px solid #002e43;
border-radius:0.5rem;
}
body.dark a {
text-decoration: none;
color: #778899;
border-bottom: 1px dotted #d5c4a1;
font-style: italic;
}
</style>
</head>
<body>
<div id="app">hello</div>
<button id="mode" class="btn">Toggle dark mode</button>
</body>
</html>
You have wrapped the checking of stored preference in the toggle method. So when you navigate to the second page, it doesn't read the value from localstorage until toggle method is invoked.
Adding a StackBlitz demo
How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable