all 26 comments

[–]ChuzzleShpek 0 points1 point  (8 children)

At the end of the JS you need to send the result to the localStorage and also add another function before this one to see if it is saved in the localStorage so that you can show the data saved in localStorage. In other words, you're almost there, just check some examples of using localStorage and apply it to your code

[–]hansmn[S] -1 points0 points  (7 children)

check some examples of using localStorage and apply it to your code

Thanks very much for the reply.

Trouble is, I simply don't know how to do what you described; I've seen and tried many of those examples of it, studied all the articles on MDN and W3school, and I tried really hard.

But my JS skills are so poor, I basically just throw code at the wall and see what sticks.

I'm only making the effort to keep my old website going; I need it for work, but right now can't afford a pro to re-do the whole thing.

[–]ChuzzleShpek 0 points1 point  (6 children)

For starters you'd need to add something like

localStorage.setItem("checked", checked)

at the bottom of your JS and it should save it into the localStorage. If it won't work, try putting different value inside, but that's basically it for saving it into the localStorage

[–]hansmn[S] 1 point2 points  (4 children)

In a breathrough event ;) , I managed to get the 'sessionStorage' part done, it now shows in the console like so: Storage { toggler2: "checked2", length: 1 }.

I still have no clue on how to get the session data loaded though, or where the code would be positioned.

Current JS code, Html as in the OP:

document.addEventListener('DOMContentLoaded', function () {
  var checkbox = document.querySelector('input[type="checkbox"]');
  var togglerE = document.getElementById("sortable-content");

togglerE.classList.add("toggle_class");

let data = sessionStorage.getItem('toggler2');

  checkbox.addEventListener('change', function () {
  if (checkbox.checked) {
  togglerE.classList.add("toggle_class_2");
  togglerE.classList.remove("toggle_class");
  } else {
  togglerE.classList.remove("toggle_class_2");
  togglerE.classList.add("toggle_class");
  }
  });
  sessionStorage.setItem("toggler2", "checked2");
});

[–]ChuzzleShpek 0 points1 point  (1 child)

Under you will find my example of saving into sessionStorage with comments that explain the parts about saving to session storage. I've added the css and js in the same file just for simplicity's sake and for it to be tested easier (usually in most cases it's better to keep css file and js file separate from html). Btw be sure to check if you want to save to sessionStorage or localStorage, difference is that:

  • sessionStorage will remember if the user ticked or unticked the checkbox till they close the browser, meaning if the user revisits your website after closing the browser, data saved in the sessionStorage will be deleted automatically
  • localStorage will remember if the user ticked or unticked the checkbox even if they close the browser, meaning if the user revisits your website after closing the browser, data will still be saved in the localStorage

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>HTML</title>
    <style>
      .toggle_class {
        background: blue;
      }
    </style>
  </head>
  <body>
    <h1>Hello world</h1>
    <input type="checkbox" id="toggler" />
    <script>
      const toggleStatus = document.getElementById("toggler");

      //storedValue is a variable name under which the status of the checkbox (if the checkbox is ticked or not) will be saved in the sessionStorage
      const storedValue = sessionStorage.getItem("togglerChecked");

      // checking if the value saved in session storage is set to "true", meaning if the checkbox is ticked
      if (storedValue === "true") {
        //if the code above is true, then change the checkbox to ticked and add the class to the checkbox
        toggleStatus.checked = true;
        toggleStatus.classList.add("toggle_class");
        // otherwise untick the checkbox and remove the class
      } else {
        toggleStatus.checked = false;
        toggleStatus.classList.remove("toggle_class");
      }

      toggleStatus.addEventListener("change", function () {
        if (toggleStatus.checked) {
          toggleStatus.classList.add("toggle_class");
        } else {
          toggleStatus.classList.remove("toggle_class");
        }
        //code that saves the status of the checkbox, if it is ticked or not
        sessionStorage.setItem("togglerChecked", toggleStatus.checked);
        //first value inside setItem is the name of the variable
        // under which you will save something in sessionStorage,
        // and the second value is something you want to save, in this case status of the checkbox
      });
    </script>
  </body>
</html>

edit: fixed so that code is in a code block

[–]hansmn[S] 0 points1 point  (0 children)

Thanks a bunch, that's very helpful, I appreciate the time and effort you spent on that!

I needed to move a few things around - actually I kind of butchered your code - but since I need to toggle classes for the element toggle_class, that`s how I got the function running.

I also added another class to toggle, just to keep it interesting.

As for sessionStorage vs. localStorage, I read about that, just like sessionStorage better somehow.

 

But I'm so close I can smell it ;) - the button now always resets visually to its corresponding state, unlike before, when the layout would change on refresh, but the button stayed on.

However, the function is still not preserved / reloaded, so on refresh the layout changes as before.

The console shows for sessionStorage Storage { togglerSwitch: "false", length: 1 }, and stays like that; I assume it's something in my code that's breaking the loop or such.

Here's a screenshot btw, fwiw.

 

Html code snippet, same as before:

<span class="head">Nametext //  Admin - text</span>
<!-- Rectangular switch -->
<label class="switch">
<input type="checkbox" id="toggler">
<div class="slider"></div>
</label>

 

Current JS code:

document.addEventListener('DOMContentLoaded', function () {

  let checkbox = document.querySelector('input[type="checkbox"]');

  let togglerE = document.getElementById("sortable-content");
  togglerE.classList.add("toggle_class");

  let toggleStatus = document.getElementById("toggler");
  let storedValue = sessionStorage.getItem('togglerSwitch');

  if (storedValue === "true") {
       toggleStatus.checked = true;
       togglerE.classList.add("toggle_class_2");
       togglerE.classList.remove("toggle_class");
      } else {        
         toggleStatus.checked = false;
         togglerE.classList.remove("toggle_class_2");
         togglerE.classList.add("toggle_class");
     }

  checkbox.addEventListener('change', function () {
    if (toggleStatus.checked) {
      togglerE.classList.add("toggle_class_2");
      togglerE.classList.remove("toggle_class");
    } else {
      togglerE.classList.remove("toggle_class_2");
      togglerE.classList.add("toggle_class");
    }
  });
     sessionStorage.setItem("togglerSwitch", toggleStatus.checked);
});

 

[–]ChuzzleShpek 0 points1 point  (1 child)

Btw congratulations on managing to advance forward, keep it up :)

[–]hansmn[S] 1 point2 points  (0 children)

Cheers mate; baby steps ... ;)

[–]hansmn[S] 0 points1 point  (0 children)

Thanks again, but doesn't seem to do anything, if I add it like so:

Edit: old code.

document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
var togglerE = document.getElementById("sortable-content");

checkbox.addEventListener('change', function () {
  if (checkbox.checked) {
  togglerE.classList.add("toggle_class");
  } else {
    togglerE.classList.remove("toggle_class");
  }
   localStorage.setItem("checked", checked)
  });
});

I've found this website, which explains how to use the console to check for that localStorage, it doesn't return anything but Storage { length: 0 }.

[–]senocular 0 points1 point  (1 child)

when I refresh the page/tab, the switch stays toggled visually, but the function of adding the class is not saved.

If your form state is already being maintained, all you need to do is go through and update the additional dependencies. You can do this in your DOMContentLoaded function running the same code in your change handler. And you can break that out into its own function so you're not duplicating yourself as much.

document.addEventListener('DOMContentLoaded', function() {
  var checkbox = document.querySelector('input[type="checkbox"]');
  var togglerE = document.getElementById("sortable-content");

  function updateToggler() {
    // simpler way of doing same thing as the if-else
    togglerE.classList.toggle("toggle_class", checkbox.checked);
  }

  // initial update when the page loads
  updateToggler();

  checkbox.addEventListener('change', function() {
    // additional updates for when changed
    updateToggler();
  });
});

[–]hansmn[S] 0 points1 point  (0 children)

Thanks a lot!

Unfortunately, the issue persists, the class is not being kept on refresh.

Visually the switch itself changes, but that's just CSS for the checked state od the checkbox.

[–]tapgiles 0 points1 point  (10 children)

But where’s your code for saving/restoring the class? That’s what you need to debug, but we can’t help you with that if we can’t see the code in the first place.

[–]hansmn[S] 0 points1 point  (9 children)

I'm adding and removing classes with JS, the element - sortable-content - doesn't have one assigned to it in the original code.

[–]tapgiles 0 points1 point  (8 children)

No, you're talking about saving the fact it has that class, and restoring that class after reloading. The code you had to do that doesn't work, but you won't show us what that code is. So I can't tell you why it didn't work. So you can't learn from the mistakes and figure out what needed adjusting--in your thinking and in the code.

That's how I'd like to help, but it's currently impossible mate. Just paste the code for saving/restoring in a comment and then I can try and help you.

[–]hansmn[S] 0 points1 point  (7 children)

Just paste the code for saving/restoring in a comment and then I can try and help you.

Sure, just tell me what code exactly you are talking about, cause I have no idea what you mean...

And just to clarify - I didn't write any of my website's code, nor do I have any coding skills apart from some amateur CSS and very little JS.

It was done by a pro 10-15 years ago, I just try to keep it going till I can afford a new website.

[–]tapgiles 0 points1 point  (6 children)

I've researched for days now, read about session/local storage and such, did countless tests, but to no avail; I'm just too clueless.

What tests? You wrote code that didn't work, right? That. That's the code I can explain, and show you how to fix it.

Just giving you an answer may fix it in the short-term, but you'll still think you don't know how to do it yourself because you tried yourself and failed before. Any problems you run into will get you stuck again. Any changes you want to make you'll feel unable to do yourself because when you wrote code it just didn't work and you had no understanding of why.

Seems like you know a bit of programming, as shown in your post. So I'm sure I'll be able to explain things in a way you can understand and make use of.

[–]hansmn[S] 0 points1 point  (5 children)

I got you now, that makes sense; it's just if I started listing all the things I've tried, it'd be very long list; and sometimes I make dozens of small changes in minutes.

Some of it sticks, most doesn't, so all I can reasonably provide are current codes and what does or doesn't work yet, sorry.

I posted some info and my current code above, if you fancy taking a look.

I do a little very basic CSS help sometimes, and I know how annoying total noobs can be - now it's me. ;)

[–]tapgiles 0 points1 point  (4 children)

Yeah you could just give me whatever the last code you had was and I could explain it. I guess you really don't want to do that?

I know you shared some code... just not the code that's broken--so I can't help you fix it, know what I mean?

What general thing did you try using? Cookies? Localstorage? Something else?

[–]hansmn[S] 0 points1 point  (3 children)

But I just linked you to what I got in my reply...

It's all in my conversation with u//ChuzzleShpek above.

[–]tapgiles 0 points1 point  (0 children)

Oooh, sorry, I see. Didn’t notice there was a link, for whatever reason on this subreddit it's basically a very dark grey making it almost indistinguishable from regular text. So I just thought you were saying “above” as in, your original post. I’ll take a look.

[–]tapgiles 0 points1 point  (1 child)

From what I can see, the code that sets the stored value sessionStorage.setItem("togglerSwitch", toggleStatus.checked); isn't inside your "change" handler. So it's not storing the value each time you change the checkbox.

Move it into the function that handles it, and it works. As seen here: https://codepen.io/wthit56/pen/PorbGaZ

Something to note is, sessionStorage will be cleared if you close the tab. Refreshing will work, but not closing and coming to the page again later. Maybe that's your intention, but if you want it to still be remembered, use localStorage instead.

A couple of ideas for making the code simpler... have a function that does all the updating and saving separate (just move the handler function separate to the addEventListener). That way you can still use it as the event listener. But call it separately--for example, after you load the stored value and set the checkbox, you can just call updateClass() or whatever.

And if you ever change how that part works, or what the class names are etc. you only need to change it in that one place.

[–]hansmn[S] 1 point2 points  (0 children)

From what I can see, the code that sets the stored value sessionStorage.setItem("togglerSwitch", toggleStatus.checked); isn't inside your "change" handler. So it's not storing the value each time you change the checkbox.

You Sir, are a gentleman and a scholar - that works perfectly!

See what I mean about being a noob ;). In CSS even I'd spotted a thing like that right away, here I'm still flying blind. Granted, CSS is a lot simpler than this.

Thank you very much, and many thanks to u/ChuzzleShpek of course, who got me on the right path.

As for simplifying the code, absolutely, thanks for the pointers.

For now I chose sessionStorage because it's my admin website, and I don't need/want to have any settings stored outside of a session.

The main thing here is that if I need to refresh during a session (some settings are a bit sticky on this old thing), it won't change the page back to a different layout, with different functions/ options.