« Previous entry | Next entry » Browse > Snippets
Skip to comments (28)
Javascript Cookie Class
Posted by nir_tayeb on Jun 13 2006 @ 15:03 :: 6190 unique visits
About
This class used for create and get cookies in the client side by javascript with High Level API.
The class
CODE: JAVASCRIPT
function Cookie(){
var name, value, expires, path="/", domain, secure=false;
this.setName = function(sName){ name=sName; }
this.getName = function(){ return name; }
this.getValue = function(){
return unescape(
(value instanceof Array)?
value.join("&"):
value
);
}
this.setValue = function(sValue){ value=escape(sValue); }
this.add = function(key, val){
if(!(value instanceof Array)){
var temp = value;
value = [];
if(temp){
value[value.length] = temp;
}
}
value[value.length] = key+"="+escape(val);
}
this.setExpires = function(date){ expires=date; }
this.getExpires = function(){ return expires; }
this.setDomain = function(sD){ domain=sD; }
this.getDomain = function(){ return domain; }
this.setSecure = function(scr){ secure = !!scr; }
this.getSecure = function(){ return secure; }
this.save = function(){
if(name && value){
if(value instanceof Array){
// if the value is as array, we join the array
value=value.join("&");
}
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
}
this.remove = function(){
// The cookie removed if the expires date is before today
expires = new Date(new Date().getTime()-1000*60*60*24);
this.save();
}
};
Cookie.get = function(name){
/*
the document.cookie return a string contains all the cookies available in the browser for the specific domain in format of: Name=Value;Name=Value;Name=Value
this function take only the cookie with the requested name and return a Cookie object with it's value.
if there isn't a cookie with the requested name, the function returns an empty cookie object with the requested name
*/
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
var cookie = new Cookie();
if ( !((( !start ) && ( name != document.cookie.substring( 0, name.length ) )) || (start==-1) ) ) {
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
cookie.setValue(unescape( document.cookie.substring( len, end ) ));
}
cookie.setName(name);
return cookie;
}
var name, value, expires, path="/", domain, secure=false;
this.setName = function(sName){ name=sName; }
this.getName = function(){ return name; }
this.getValue = function(){
return unescape(
(value instanceof Array)?
value.join("&"):
value
);
}
this.setValue = function(sValue){ value=escape(sValue); }
this.add = function(key, val){
if(!(value instanceof Array)){
var temp = value;
value = [];
if(temp){
value[value.length] = temp;
}
}
value[value.length] = key+"="+escape(val);
}
this.setExpires = function(date){ expires=date; }
this.getExpires = function(){ return expires; }
this.setDomain = function(sD){ domain=sD; }
this.getDomain = function(){ return domain; }
this.setSecure = function(scr){ secure = !!scr; }
this.getSecure = function(){ return secure; }
this.save = function(){
if(name && value){
if(value instanceof Array){
// if the value is as array, we join the array
value=value.join("&");
}
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
}
this.remove = function(){
// The cookie removed if the expires date is before today
expires = new Date(new Date().getTime()-1000*60*60*24);
this.save();
}
};
Cookie.get = function(name){
/*
the document.cookie return a string contains all the cookies available in the browser for the specific domain in format of: Name=Value;Name=Value;Name=Value
this function take only the cookie with the requested name and return a Cookie object with it's value.
if there isn't a cookie with the requested name, the function returns an empty cookie object with the requested name
*/
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
var cookie = new Cookie();
if ( !((( !start ) && ( name != document.cookie.substring( 0, name.length ) )) || (start==-1) ) ) {
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
cookie.setValue(unescape( document.cookie.substring( len, end ) ));
}
cookie.setName(name);
return cookie;
}
The code is based on the setcookie/getcookie functions of "Top 10 custom JavaScript functions of all time".
How to use this class?
CODE: JAVASCRIPT
// Create a new cookie and save it
var c = new Cookie();
c.setName("test");
c.setValue("val");
c.save();
var c1 = new Cookie();
c1.setName("test1");
c1.add("key1","value1");
c1.add("key2","value2");
c1.save();
// Get a cookie and alert it's name and value
var c2 = Cookie.get("test");
alert(c2.getName() + ":" + c2.getValue());
// Remove the cookie
c.remove();
var c = new Cookie();
c.setName("test");
c.setValue("val");
c.save();
var c1 = new Cookie();
c1.setName("test1");
c1.add("key1","value1");
c1.add("key2","value2");
c1.save();
// Get a cookie and alert it's name and value
var c2 = Cookie.get("test");
alert(c2.getName() + ":" + c2.getValue());
// Remove the cookie
c.remove();
28 comments posted so far
Add your own »
2. On Jun 13 2006 @ 22:57 DooM wrote:
Nice class, really helpful in management of user personal settings(like language, skins etc).3. On Jun 14 2006 @ 11:51 Matthijs wrote:
Usefull class! good work4. On Jun 14 2006 @ 13:18 silverstrike wrote:
Is this Efficient?Look's real good. What about some serious documentation?
5. On Jun 14 2006 @ 13:46 nir_tayeb wrote:
Yes, this is efficient code but less then the getcookie/setcookie/deletecookie functions of the "Top 10 custom JavaScript functions of all time" (link in the post).But as a developer, who love OOP, this is more usefull than the three function above, and more *High Level* - so this is a perfect for common use.
6. On Jun 15 2006 @ 18:06 Matthijs wrote:
Why is the efficiency important? Your cookie won't hold more then 5 values or something, and it all happends clientside anyway...7. On Jun 09 2008 @ 15:45 guest wrote:
Great Job, I like it a-lot!8. On Aug 27 2008 @ 04:53 guest wrote:
Top 10 best casino roulette gambling casinos based on micro gaming platform.Best play blackjack gambling casinos, play to win and enjoy your online
casino black jack experience.
Learn how to play play video poker and experience the thrill of gambling and beating online casinos.
Use a free poker sites to calculate your winning poker odds.
Learn the art of horse racing software and play to win your punts at the races.
Dont buy movies, get online bootleg movie downloads movies and watch them for free.
Earn money and work from home, with online forex, trade the forex market.
Get all sorts of iphone software for your new iphone mobile telephone.
9. On Feb 10 2009 @ 01:36 zsdasd wrote:
<a href=http://www.mymovie-downloads.com/online_hollywood_movie_downloads.php>online movie download</a><a href=http://www.mymovie-downloads.com/how_to_download_full_dvd_movies.php>download full movies</a>
<a href=http://www.mymovie-downloads.com>bootleg movie download</a>
<a href=http://www.forextradingsystemonline.net>forex trading system</a>
<a href=http://www.forextradingsystemonline.net/learn_forex_trading_course.html>learn forex trading</a>
<a href=http://www.alternativehomeenergysources.com/build_and_make_solar_power_panel_kits.html>solar kits</a>
<a href=http://www.alternativehomeenergysources.com/home_solar_power_panels_for_energy.html>home solar power</a>
<a href=http://www.playonlineroulette.org>online roulette</a>
<a href=http://www.onlinebingo1.net>online bingo</a>
<a href=http://www.playonlinecraps.org>online craps</a>
<a href=http://www.playslotmachineonline.net>online slot machine</a>
<a href="http://www.roulettesystemwinner.com"><img src="http://www.roulettesystemwinner.com/img/online roulette" border="0" alt="online roulette"></a>
10. On Feb 10 2009 @ 01:36 zsdasd wrote:
online movie downloaddownload full movies
bootleg movie download
forex trading system
learn forex trading
solar kits
home solar power
online roulette
online bingo
online craps
online slot machine
[img]http://www.roulettesystemwinner.com/img/online roulette[/img]
11. On Mar 15 2009 @ 16:00 guest wrote:
Our wholesale replica handbags is one of the best Replica Purses wholesaler.we are selling Louis vuitton replica ,Chanel Replica ,Gucci Replica ,The handbags are Hermes Birkin ,Hermes Kelly ,Chanel 2.55 bag ,Louis vuitton replica Speedy 30 ,Louis vuitton Damier Canvas ,and we selling high and top Chanel wallet ,Louis Vuitton wallet ,Hermes belt . Choosing Replica handbags to perfect your lifestyle: Business Opportunities.Jadeshow’s replica Tiffany Jewelry and Replica Bvlgari Jewelery looks just like the real thing. Why pay more for a single piece of Tiffany Replica jewelry,Bvlgari Replica Jewelry when you can treat yourself to a number of replica pieces for the same price or less? Be simply spectacular with contemporary Tiffany-inspired jewelry!Jadwshow delights in the opportunity to offer our customers fine Tiffany Bracelets , Tiffany Necklaces , Tiffany Earrings , Tiffany Rings , Tiffany Bangles ,Gucci jewelry replica , Chanel wallet and Louis Vuitton wallet
all at remarkably low prices.
We are top designer wholesale Replica handbags ,Louis vuitton replica ,replica jewelry ,Bvlgari Replica ,Gucci Replica jewelry ,Swarovski Crystal , We offer a wide variety of high quality Tiffany inspired jewelry at very low prices. Gucci Necklaces ,Gucci Bracelets , Gucci rings , Gucci Earrings , Links Jewelry ,Chanel Rings and Tiffany replica , Cartier Jewelry more. Free shipping with any purchase over 5 items.Replica Louis Vuitton chanel replica handbag
We are the best and top Replica handbag ,replica bags ,Replica watches wholesaler in china,Our products is Replica louis vuitton handbags ,Chanel replica handbags ,Gucci replica handbags ,Miu Miu handbag and we are selling Replica wallet ,best Louis Vuitton wallet ,Chanel wallet replica,and sell Rolex replica watches ,Omega replica watches .Hermes replica bag
12. On Mar 16 2009 @ 11:07 guest wrote:
Helpful in management of user personal settings. tower defense13. On Mar 16 2009 @ 13:30 Certifications wrote:
Excellent post regarding Java script cookies class, though I found valueable article related to the topic yet needs some enhancement too. Fine effort at all.I am sure I will be back again to read but in these days I am busy in my exam<a href="http://www.free-testking.net/exam/70-284.htm">70-284</a> for Installing, Configuring, and Administering Microsoft Exchange 2003 Server about which I am confident to pass in first attempt because I have already pass <a href="http://www.free-testking.net/exam/70-297.htm">70-297</a> which is for Designing a Microsoft Windows Server 2003 Active Directory and Network so I will back again to read more.14. On Apr 02 2009 @ 13:40 Certifications wrote:
Does this work for php as well or not let me see it after my 640-863 latest designing for Cisco Internet work solutions exams which I have prepared from best Cisco training providers as I have already passed my 640-822 exam for Cisco Certified Entry Network Technician certification along with the EX0-101 ITIL Foundation v.3 Certification Exam with latest Cisco updates material available and got high score in all exams as i will be free from all this i would try that code to implement on my work.15. On Apr 13 2009 @ 13:50 Valencia wrote:
I am currently learning the web development using PHP, Java Script etc. I have a tutorial for this purpose. You have introduced a great script. I will try this after my 70-640 Exam. I have a friend who is also want to learn PHP but she is also preparing for PMI-001 exam. After giving the exam, I am also thinking about going for Microsoft 70-649 Exam. I will come back again. Keep on doing great work like this.16. On May 11 2009 @ 11:41 guest wrote:
QIXINYANWay to teach a dog infected with love and enjoyment of the people around them is dog training. Not all the people who keep the dog know how to train a puppy, but who often find it impossible to carry out dog obedience training , people who have a different feel that they do so. Although some people will tend to the field of veterinary medicine, other people will choose more specific career dog. Perhaps the most popular dog-centric professional area is that dog training.
Police dog training is a great way for those who love the dogs, to help them use and dissemination of information. One important thing to remember is that the dog trainer can not only teach dog tricks and working dogs and their masters. In fact, owners tend to play a bigger roll than the dogs training process.
Some people choose to learn some dog training tips from an experienced coach or a veterinary surgeon of similar projects in the apprenticeship. This is often useful, because many of these puppies training experience in the field and constant practice. Customers will often choose a coach approved no more than one certification. Other routes may be the next dog learning how to train a puppy through the animal science program behavior.
Do you know how to lose weight? No matter how you do, do not skip breakfast. People who began the day a good healthy breakfast does not have loss weight diet throughout the day than those who do not eat breakfast. Or, if you prefer to drink your breakfast to reach weight loss, fruit juice is a good choice. All you need to do is the integration and go! Super simple!
In addition, how to lose pounds? Plan your meals so you eat every 3-4 hours, about 5-6 times a day. Do you want to ensure that your last meal is 3-4 hours, and then go to bed. It seems to eat more frequently in the first strange, but studies ways to lose weight by the books and internet, you’ll not only lose pounds success, but also have the energy level of the day.
Are you annoying with belly fat? I am sure you hear that sit-ups are one of the best belly fat exercises. How to lose belly fat? There are not only belly fat exercises, but have belly fat diet. Although it is entirely correct sit-ups will strengthen the abdominal muscles and make you more powerful in this regard, you may get rid of belly fat because you’re fat to improve the muscle to hold better, which in fact did not lose belly fat itself.
The key to lose belly fat is actually quite simple. Therefore, these two key points, first of all to take action to belly fat exercises, second, have belly fat diet every day. Do these, you will lose belly fat!
As a child, you can find kids jobs to get money. If not, maybe you are considering how to make children work in additional funds. jobs for 15 year olds are so many. However, we know that you will not find a real job; you just need a working pocket money. Finding jobs for 16 year olds is not a difficult task.
To make money online, first you need to make necessary preparations. In any field or industry you need in all walks of life through appropriate channels to meet their own, in order to succeed. Can you imagine how to starting your own business? It would be a good way to Make Money on the Internet and move forward at full speed is going to just be disastrous.
In the network marketing, you can set up shop online, start flower shop, or you can start carpet cleaning business.In my opinion, there are also other popular ways to make money,for instance, So starting a laundromat business at home, another way is to manage furniture making business at home.
17. On May 16 2009 @ 08:31 emily wrote:
I see all the site is very care fully and checked it all its the very nice blog. i don't know more bout it but i have a good business related blog and there u teach a tips and tricks about business strategy . its a very detailed and more powerful blog than others business related blogs.see this . <a href="http://businessshredding.blogspot.com/
">Business Shredding</a> - <a href="http://seo-pakistan1.blogspot.com/">Seo tips and tricks</a> - <a href="http://interiordesigne4home.blogspot.com/">Home Interior Design<a/> - <a href="http://onlinegardeningtraing.blogspot.com/">Online Gardening
</a> -
18. On May 16 2009 @ 08:35 emily wrote:
<a href="http://digitalcamerabrands.blogspot.com/">Digital camera brands</a> -19. On May 16 2009 @ 08:45 emily wrote:
I see all the site is very care fully and checked it all its the very nice blog and now u read that blog about gardening online tips and tricks <a target="_blank" href="http://onlinegardeningtraing.blogspot.com/">Online Gardening</a> -
20. On May 30 2009 @ 09:12 guest wrote:
Nice post about this java script. I got enough information about certifications and java scripts some certifications are testking 220-602, testking 350-001 and testking 640-802. I like your blog very much.21. On May 31 2009 @ 18:01 guest wrote:
gucci shoesprada shoes
dior shoes
Gucci Men's Shoes
Gucci Women's Shoes
Men Prada shoes
Men Prada Low Tops
Women Prada shoes
Women Prada Low Tops
UGG Classic Cardy Boots
UGG Classic Short Boots
UGG Classic Tall Boots
UGG Nightfall Boots
22. On Jun 09 2009 @ 09:09 guest wrote:
DVD Audio RipperFree DVD Audio Ripper
DVD Audio Ripper for Mac
DVD to MP4 Converter
DVD to MP4 Converter for Mac
DVD to iPod Converter
free DVD to iPod Converter
DVD to iPod Converter for Mac
DVD Ripper
Diablo 2 CD Key
Diablo 2 CD Keys
Free DVD Ripper
DVD Ripper for Mac
NFL Jerseys
Scoccer Jerseys
Hockey Jerseys
MLB Jerseys
NHL Jerseys
23. On Jun 17 2009 @ 11:26 guest wrote:
jobs for 14 year oldsjobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
jobs for 14 year olds
Saraideas's Blog
Sara ideas
saraideas
saraideas
saraideas
saraideas
saraideas
saraideas
saraideas
Sara's Blog
sara's Site
Saraideas
saraideas
24. On Jul 09 2009 @ 00:49 guest wrote:
chat yapsohbet yap
muhabbet yap
çet yap
chat
sohbet
chat yap
sohbet yap
sevda şiirleri[URL]
[URL="http://magazin-habercisi.blogspot.com" target="_blank"]"http://magazin-habercisi.blogspot.com" target="_blank"magazin[URL]
[URL="http://magazin-habercisi.blogspot.com" target="_blank"]"http://magazin-habercisi.blogspot.com" target="_blank"magazin haber[URL]
[URL="http://magazin-habercisi.blogspot.com" target="_blank"]"http://magazin-habercisi.blogspot.com" target="_blank"magazin dünyası[URL]
[URL="http://www.dogucafe.com" target="_blank"]"http://www.dogucafe.com" target="_blank" chat[URL]
[URL="http://www.dogucafe.com" target="_blank"]"http://www.dogucafe.com" target="_blank" sohbet[URL]
25. On Jul 11 2009 @ 04:28 sunzheng wrote:
cheap wow power levelingbuy wow gold
my wow power leveling
cheapest wow gold
CHEAP wow power leveling
BUY wow gold
MY rs gold
good wow power leveling
CHEAPEST lotro gold
cheap aion gold
buy wow gold
my wow gold
cheapest wow gold
26. On Jul 14 2009 @ 03:50 guest wrote:
buy wow goldmy wow power leveling
buy wow gold
good wow power leveling
BUY wow gold
my wow power leveling
CHEAP rs gold
cheap wow power leveling
CHEAPEST lotro gold
MY aion gold
buy wow gold
cheap wow gold
CHEAPEST wow gold
27. On Jul 14 2009 @ 07:36 guest wrote:
AVI to DVD Converter,AVI to DVD Creator,iPhone Ringtone Maker for Mac,AVI Converter OS X,VOB Converter OS X,AVCHD Video Converter,FLV Converter,PowerPoint Converter,AVCHD Converter,Blue-Ray ripper,Rip Blue Ray,FLV to MOV Mac,VOB to DVD,HD Video Converter,iPod Playlist Transfer28. On Jan 05 2010 @ 14:45 uggbaileybutton wrote:
bailey button uggs-ugg boots cheap
ugg boots uk
ugg classic
1. On Jun 13 2006 @ 22:07 uvals wrote:
Thanks :) it's great!