Hello Guys How are you ? I'm working on project and I have a simple Question How to keep the Class Togggled after refreshing the page using jQuery ??
whenever you press the button it works fine, but upon page reload it reverts back to the before toggled state. How might I fix this issue, open to any solution preferably client side? (Below is a snippet of my button and the code alongside it)
JS Code :
$(document).on("click", "#toggle_the_div", function toggleDiv(e) {
e.preventDefault();
// Change Toggle Icon
$('.icon_toggler').find('.ion').toggleClass('ion-md-radio-button-off ion-md-radio-button-on');
if ($('.icon_toggler').find('.ion').hasClass('ion-md-radio-button-on')) {
$($(this)).css("color", "var(--primary)");
} else if ($('.icon_toggler').find('.ion').hasClass('ion-md-radio-button-off')) {
$($(this)).css("color", "var(--dark)");
}
// Toggle Activation
$('#hellodiv').toggleClass('is_toggled');
if (localStorage.getItem('switch-state') && localStorage.getItem('switch-state') === "true") {
//
}
});
HTML Code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.6.3/css/ionicons.min.css">
<title>Test</title>
<style type="text/css">
#hellodiv .is_toggled {
background: red;
color: white;
padding: 10px;
}
</style>
</head>
<body>
<button type="button" id="toggle_the_div" class="btn btn-light">
<span class="icon_toggler mr-1"><i class="ion ion-md-radio-button-off"></i></span> Toggle Now
</button>
<div class="D1" id="hellodiv">
<h1>Hello World</h1>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>