PDA

View Full Version : Creating a cookie



FrickenTrevor
02-17-2015, 04:47 AM
I would like to add a cookie to this code (http://cssdeck.com/labs/turn-on-off-the-lights) but without having to use the jQuery cookie plugin. I have searched on Google for hours and couldn't find anything else. Could any one else please help?

vwphillips
02-17-2015, 10:48 AM
<!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>
<title></title>
</head>

<body>
enter a value and click a button
<input id="test" />
<input type="button" name="" value="SetCookie Days" onclick="SetCookie('test',document.getElementById('test').value,2)" />
<input type="button" name="" value="SetCookie Session" onclick="SetCookie('test',document.getElementById('test').value,null)" />
<input type="button" name="" value="Cancel SetCookie" onclick="SetCookie('test',document.getElementById('test').value,-1)" />

<script type="text/javascript">

function GetCookie(nme){
var v=Cookie(nme);
if (v&&document.getElementById(nme)){
document.getElementById(nme).value=v;
}
}

function Cookie(nme){
var re=new RegExp(nme+'=[^;]+','i');
return document.cookie.match(re)?document.cookie.match(re)[0].split("=")[1]:null;
}

function SetCookie(n,v,days){
document.cookie=n+'='+v+(typeof(days)=='number'?';expires='+(new Date(new Date().getTime()+days*86400000).toGMTString())+';path/;':';');
}

GetCookie('test');

</script>
</body>

</html>

ramarjun
02-17-2015, 03:44 PM
u must add the cookie following function,,, value of each content using jquery
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}

FrickenTrevor
02-17-2015, 10:36 PM
Appreciate the help, but I still dont know what to do with the code you provided. Here is the jQuery Code that I have that needs a cookie


$(document).ready(function() {
$('.day-night').click(function() {
$('body').toggleClass('night');
});
});