3

I've created a clock based on a fantasy timezone. I've then created an "alarm" which will execute an alert if a checkbox is ticked.

I'm trying to use local storage to make the checkbox persistent on page reload, so that people can go to other pages on the website, or refresh without having to tick the box each time.

I can't seem to get it to work though and I've been through lots of similar questions, such as this one: how to Keep checkbox checked after refresh the page

Here is a codepen of the code I have: http://codepen.io/anon/pen/xqRWJM?editors=1111

Here's the html code for the checkbox:

<div id="alert">Alert me when it's night time:
<input id="alertme" type="checkbox"></input>
</div>
Community
  • 1
  • 1
Sarah
  • 35
  • 1
  • 5
  • The example you linked shows you how to use localstorage which seems like a good approach, but I dont see that being used anywhere in your code. Could you clarify what exactly is not working for you? – Trajan Unger Mar 08 '17 at 01:23
  • I feel like I'm just putting it in the wrong place in the code or doing something equally as stupid. It should be a simple thing but my mind feels like mush after writing up the rest of the code. I'm kind of new to using cookies and local storage. I've tried the code from the question but it doesn't seem to work when I reload the codepen preview. http://codepen.io/anon/pen/aJBKbZ?editors=1011 – Sarah Mar 08 '17 at 01:26
  • You didn't add the jquery library in codepen, it's seems work after adding the jqeury library. – user2970115 Mar 08 '17 at 01:40
  • I knew it would be something simple.. Thank you! – Sarah Mar 08 '17 at 01:49

1 Answers1

0

I've made a simple pen for you which demonstrates how to save the checkbox state with the LocalStorage API. Hopefully you can adapt this to fit your specific needs.

http://codepen.io/oculusriff/pen/RpoJWQ?

HTML

<input type="checkbox" id="test" /> <label for="test">Test</label>

JavaScript

function App() {}

App.prototype.setState = function(state) {
  localStorage.setItem('checked', state);
}

App.prototype.getState = function() {
  return localStorage.getItem('checked');
}

function init() {
  var app = new App();
  var state = app.getState();
  var checkbox = document.querySelector('#test');

  if (state == 'true') {
    checkbox.checked = true;
  }

  checkbox.addEventListener('click', function() {
      app.setState(checkbox.checked);
  });
}

init();

Cheers, Josh

Joshua Russell
  • 670
  • 5
  • 13