How to assign a class to a block (but after reloading the page the class should remain)? At first I thought I needed to use cookies, but advised localStorage . I read, I understood how to extract data from localStorage , but I still did not understand how to explain and write to localStorage, for example, that a block is assigned or removed a class, and attach this class if it is written to localStorage .

I wrote the code below, but I do not even know the degree of its fallacy.

 $(document).ready(function() { if (localStorage.getItem('block')= true) { $('.block').addClass('active'); } }); $("input").click(function() { $(this).siblings('.block').toggleClass('active'); if (localStorage.getItem('block') = true) { localStorage.removeItem("block", "active"); } else { localStorage.setItem("block", "active"); } }); 
 .block { display: block; position: relative; width: 80%; height: 100px; margin: 0 auto; background: #4DB6AC; } .block.active { background: #FFC107; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="block"></div> <input type='button' value='Переключатель'> 

    1 answer 1

    First you need to fix the obvious errors "=" is not the same as "==".

    Here is your code on codepen that works.

     ... if (localStorage.getItem('block') == 'active') { $('.block').addClass('active'); } ... 

    ps And carefully study the basics of JavaScript.