1
\$\begingroup\$

I put together a code will allow me to toggle a class and save it in local storage.

Now I need to add 2 more classes to be toggled and be saved in the same manner. I don't know how to iterate properly with the code and the DOM to achieve this.

This is my "semi-working" example: http://jsbin.com/nimekebura/1/edit?html,css,js,output

HTML:

    <a href="javascript:void(0)" class="bar-toggle">toggle and save state</a>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

<hr />

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

<hr />

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

<hr />

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

JS:

 //retrieve current state
 $('.container').toggleClass(localStorage.toggled);

    /* Toggle */
    $('.bar-toggle').on('click',function(){

     // set 1 localstorage values are always strings (no booleans)  
       if (localStorage.toggled != "with_toggle" ) {
          $(".container").toggleClass("with_toggle", true );
          localStorage.toggled = "with_toggle";

       } else {
          $(".container").toggleClass("with_toggle", false );
          localStorage.toggled = "";
       }


    });

I need to add and toggle another 2 classes to each .box class already in the code.

so the code would toggle like this:

<div class="container with_toggle">
  <div class="box multi box_toggled"></div>
  <div class="box multi box_toggled"></div>
</div>

what would be the best code practice to achieve the above?

Also Iwas told, the localStorage object is not meant to be extended with new keys like toggled and If wanted to add a new item, I would need to you use localStorage.setItem('key', 'value') https://developer.mozilla.org/en-US/docs/Web/API/Storage

Needless to say I have no idea how to do this the best code practice way. Could someone help me refactor the code properly and also add the two new classes?

\$\endgroup\$
1
\$\begingroup\$

The following are all acceptable ways to set/get values to/from localStorage (or sessionStorage for that matter):

// set
localStorage.key = 'value';
localStorage['key'] = 'value';
localStorage.setItem('key', 'value');

// get
value = localStorage.key;
value = localStorage['key'];
value = localStorage.getItem('key');

I think from a practical standpoint though, you might see explicit setItem() or getItem() method calls used most frequently, as oftentimes one might find themselves working with dynamic key names, which would eliminate the first usage example from each of the the sets above. Oftentimes developers choose to simply be consistent and use the getter/setter methods rather than mix direct property access when key names are known vs. getter/setter or "array-like" access when the key names are dynamic.

More complex applications may also abstract out direct access to localStorage and sessionStorage altogether, especially when dealing with browsers that do not support web storage (and therefore may need cookie-based fallback). In such cases, you would absolutely not be able to have hard-coded key names when interacting with the underlying web storage, because you might have a usage pattern like:

myStorage.set(key, value, inSession) {
    if (typeof Storage !== undefined) {
        // we have local and session storage available
        if(inSession === true) {
            sessionStorage.setItem(key, value);
        } else {
            localStorage.setItem(key, value);
        }
    } else {
        // fallback
    }    
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ In other words my implementation is not necessarily wrong? Its juts not very common \$\endgroup\$ – user2513846 Oct 26 '16 at 3:14
  • 1
    \$\begingroup\$ @user2513846 I would not even go so far as to say it is uncommon. I would just say that in typical professional codebases, I tend to see getters/setters used more frequently than property-style access. I also tend to see a lot of abstractions over the web storage API's like that shown in my example or cases where the abstraction performs some sort of function on top of the web storage layer such as JSON serialization/deserialization or type juggling operations (since Web Storage only persists as strings). \$\endgroup\$ – Mike Brant Oct 26 '16 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.