javascript - Change Color Themes - How To Prevent the Site Goes Back to Default -
i have default css file website , link master page.
<link href="~/content/blue/maincss.css" rel="stylesheet" title="main" />
then, have jquery code change color theme below
$(".greensquare").on('click', function (e) { $('link[title="main"]').attr('href', '~/content/green/maincss.css'); e.preventdefault(); });
the function works well, when greensquare click, site color changed green. however, after page loaded, goes default color theme, unfortunately.
how prevent site goes default color? thanks,
edit storage involved
$(".greensquare").on('click', function set_theme(theme) { $('link[title="main"]').attr('href', '~/content/green/maincss.css'); }); if (typeof (storage) !== "undefined") { function set_theme(theme) { $('link[title="main"]').attr('href', '~/content/green/maincss.css'); if (supports_storage) { localstorage.theme = theme; } if (supports_storage) { var theme = localstorage.theme; if (theme) { set_theme(theme); } } else { } } }
but somehow doesn't work, yet.
you use window.localstorage save color information across page loads.
<!doctype html> <html> <head> <title>cookie</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <link href="" rel="stylesheet" title="main" /> <script type="text/javascript"> $(document).ready(function(){ // when page loads, cookie value. var currentcolor = localstorage.getitem('my_bgcolor'); // if find if (currentcolor === "green") { $('link[title="main"]').attr('href', 'green.css'); } if (currentcolor === "red") { $('link[title="main"]').attr('href', 'red.css'); } if (currentcolor === "") { $('link[title="main"]').attr('href', 'green.css'); } $(".greensquare").on('click', function(e) { e.preventdefault(); $('link[title="main"]').attr('href', 'green.css'); // set storage item 'green'. localstorage.setitem('my_bgcolor', 'green'); }); $(".redsquare").on('click', function(e) { e.preventdefault(); $('link[title="main"]').attr('href', 'red.css'); // set storage item 'red'. localstorage.setitem('my_bgcolor', 'red'); }); }); </script> </head> <body> <a href="#" class="greensquare" id="green">click me</a> <a href="#" class="redsquare" id="red">click me</a> </body> </html>