1

My jquery code : Please let me know how to keep class after reload page

$(document).ready(function(){   
  $("#themecolors li a").click(function(){
    $("#themecolors li a").removeClass("working");
    $(this).addClass("working");
  });

  $(".default-theme").click(function() {
    $("body").removeClass();
    $("body").addClass("one");
  });
 $(".green-theme").click(function() {
    $("body").removeClass();
    $("body").addClass("green_skin");           
    });
});
Manish Kumar
  • 33
  • 1
  • 4
  • 2
    Persist the values into `localStorage` / `sessionStorage` when they change. Read them and apply them on page load – Phil Jul 31 '18 at 06:35
  • Please let me know how to persist the values in localStorage / sessionStorage. And how can add this code. – Manish Kumar Jul 31 '18 at 06:41
  • I highly recommend you read the documentation and discover _"how"_ yourself ~ https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – Phil Jul 31 '18 at 06:42

3 Answers3

5

Check below code. You can add class value in local storage on click. ans use that local storage on document ready.

 $("#themecolors li a").click(function(){
    $("#themecolors li a").removeClass("working");
    $(this).addClass("working");
    localStorage.ClassName = "working";
  });

$(document).ready(function() {
    SetClass();
});

function SetClass() {
//before assigning class check local storage if it has any value
    $("#themecolors li a").addClass(localStorage.ClassName);
}
Ketan Vaghasiya
  • 384
  • 4
  • 13
0

You can use your code like this

jQuery(window).on("load", function() {
  $("#themecolors li a").click(function(){
  $("#themecolors li a").removeClass("working");
  $(this).addClass("working");
});

$(".default-theme").click(function() {
  $("body").removeClass();
  $("body").addClass("one");
});
$(".green-theme").click(function() {
 $("body").removeClass();
 $("body").addClass("green_skin");           
 });
});
Debasish
  • 322
  • 6
  • 23
  • I want add class on click and after page reload or refresh remain add same. – Manish Kumar Jul 31 '18 at 06:49
  • You can use jQuery(window).on("load", function() { /* code */}); instead of $(document).ready(function(){ }); i also update this code please check. – Debasish Jul 31 '18 at 10:16
-1

When page is reload, the JS files will be downloaded again, so you cannot save within JS the state.

You can use cookies for this. See here: How do I set/unset a cookie with jQuery?

Frighi
  • 475
  • 4
  • 17