I have 2 links ('black' & 'white').
I wish for the user to click on one of these links in order to addClass and removeClass to the body and for that change of body class to persist throughout as the user browses other pages of the website (or indeed on their revisit for a set period after also).

I have the addClass/removeClass thing working but don't know how to add the cookie so that the class is carried over to subsequent pages that the user visits. There's a tutorial here http://www.ilovecolors.com.ar/using-cookies-jquery/ that does almost what I want however I can't tweak the code in the demo so that it applies the class to the body (in the demo it changes the class of the actual link that the user clicks on). I have had a good go - honest - but I give in - could someone please give me a hand here :)

Here's my sample page that I need help with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
body { color:red; margin:40px; }
p { width:400px; margin:40px 0; }
.switcher { background:black; }
 </style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

</head>
<body>
<p>I want the user to be able click 'Black' or 'White' and for the class 'switcher' to be added (by clicking 'Black') or removed (by clicking 'White') to 'body' and for that preference to by carried over (by using a cookie) to the subsequent pages they visit whilst on the site.</p>
  <a href="#" id="addClass">Black</a><br />
  <a href="#" id="removeClass">White</a>
  
<script type="text/javascript">
    $("#addClass").click(function () {
	  $('body').addClass('switcher');
    });
	$("#removeClass").click(function () {
	  $('body').removeClass('switcher');
    });
</script>
</body>
</html>

Dani AI

Generated

Good start — is right: persist the choice when the click happens and reapply it on page load. 's create/read cookie approach works; below are safer, modern options and short tips to make the behavior more robust across pages and devices.

A simple, reliable alternative is to use localStorage for a client-only preference (no cookies sent to the server, simpler API). Example pattern:

<script>
document.addEventListener('DOMContentLoaded', function(){
  if (localStorage.theme === 'switcher') document.body.classList.add('switcher');
  document.getElementById('addClass').addEventListener('click', function(e){
    e.preventDefault();
    localStorage.setItem('theme','switcher');
    document.body.classList.add('switcher');
  });
  document.getElementById('removeClass').addEventListener('click', function(e){
    e.preventDefault();
    localStorage.removeItem('theme');
    document.body.classList.remove('switcher');
  });
});
</script>

Quick best-practice notes: if you must use cookies, keep the value tiny, use encodeURIComponent, set a sensible expiry, and on HTTPS specify Secure and SameSite flags. Cookies are sent with every HTTP request and have size limits (keep them small). Consider respecting the users system preference withprefers-color-scheme` as your default, and always test keyboard focus and contrast when changing themes so accessibility is preserved.

Recommended Answers

All 2 Replies

When the click occurs you have to set the cookie, and then on the page load function you have to check the cookie and apply the class again.

Hi, I finally have this resolved. Thanks for the help. Here's my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title></title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
#container.uk-content .us, #container.us-content .uk { display:none; }
 
</style>
</head>
<body>
<div id="container" class="uk-content">

<ul>
<li><a href="#">uk-content</a></li>
<li><a href="#">us-content</a></li>
</ul>

      <div class="uk">UK content</div>
      <div class="us">US content</div>
</div>
</body>
<script>
    $(function() {
        $("ul a").click(function() {
            var countryswitch = $(this).text();
            $("#container").removeClass().addClass(countryswitch);
            createCookie("countryswitch",countryswitch);
            return false;
        });
        
        if (readCookie("countryswitch") != null) {
          $("#container").removeClass().addClass(readCookie("countryswitch"));
        
        }
        else
        {
          $("#container").removeClass().addClass("uk-content");
        }

    });
    
    function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

    

</script>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.