Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  82] [ 5]  / answers: 1 / hits: 23181  / 15 Years ago, wed, april 29, 2009, 12:00:00

How can you remove a class name and replace it with a new one?



<style>
.red {background-color: #FF0000;}
.green{background-color: #00FF00;}
.blue {background-color: #0000FF;}
</style>

<body class=red>
<ul>
<li><a href=>red</a></li>
<li><a href=>green</a></li>
<li><a href=>blue</a></li>
</ul>
</body>


In this case when you click on red or green or blue, the body class name will change accordingly. Also it will make a cookie which will save the choice.



I tried the jQuery .addClass and it's working, but it's adding a class on top of the existing one. Also I can't manage to save the cookie.


More From » jquery

 Answers
7

Use:



$('.red').removeClass('red').addClass('blue');


Here's the full working code:



$(function() {
$(a).click(function() {
var color = $(this).text();
$(body).removeClass().addClass(color);
return false;
});
});


And now for the cookie part



$(function() {
$(a).click(function() {
var color = $(this).text();
$(body).removeClass().addClass(color);
createCookie(color,color);
return false;
});

if (readCookie(color) != null) {
$(body).removeClass().addClass(readCookie(color));

}
else {
$(body).removeClass().addClass(red);
}
});

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);
}


Working example here. A thank you to QuirksMode for the pre-made cookie code (cookie-cutter cookie code?)


[#99628] Thursday, April 23, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tajo

Total Points: 415
Total Questions: 124
Total Answers: 103

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
tajo questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Wed, Jan 26, 22, 00:00, 2 Years ago
Tue, Dec 1, 20, 00:00, 3 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;