I have a button with some jquery, this button toggle the theme from dark to light or light to dark. I want to keep this button enabled even after the page refreshing or changing to another page. What should I do!
I have a button with some jquery, this button toggle the theme from dark to light or light to dark. I want to keep this button enabled even after the page refreshing or changing to another page. What should I do!
You have to store the data in cookies or Session with PHP.
That way even when the page is refreshed, the changes will be saved.
You can also store the data in cookies with JavaScript.
Lets say the user changed the background color to #33FFEA.
To store th background color in cookies, you can use this code:
localStorage.setItem("backgroundColor", "#33FFEA");
And now for recieving the data back from cookies, you can use this code:
document.body.style.backgroundColor=localStorage.getItem("backgroundColor");
For adding the saved color directly to the <body> on page load, use this code (Compiled code):
<body onload="LightDarkMode()">
<script>
funtion LightDarkMode()
{
document.body.style.backgroundColor=localStorage.getItem("backgroundColor");
}
</script>
You have to remember that the color has already been stored in the cookies for the above code.
you can use a local storage mechanism to achieve this, I assume you have a function like below to change the theme
function change_theme(){
/*your change theme jquery*/
localStorage.setItem("theme",'your css class'); //setting theme to local storage
}
To get this on page load
$( document ).ready(function() {
var theme = localStorage.getItem('theme'); //getting back theme from localstorage
$( "body" ).addClass(theme); //adding class to body tag
});