Create, Read, Update, and Delete Cookies with MooTools

By  on  

MooTools features the ability to create, read, update, and delete cookies. Lets look at how we can use MooTools to control cookies.

Cookie Syntax

The syntax of the cookie, as laid out by the MooTools documentation, is:

var myCookie = Cookie.write(key, value[, options]);

The options include:

  • domain: the domain for which the cookie will be written
  • duration: the length, in days, that the cookie will last
  • path: specific path the cookie belongs to
  • secure: a true/false value specifying if the cookie should be placed as secure

 

Creating a Cookie

	var cookie  = Cookie.write('handle', 'SoccerStar23', {duration: 30, domain: '.davidwalsh.name'}); //save for a month

The above code creates a cookie that will last for 30 days at the root directory on the "davidwalsh.name" domain.

Updating the Cookie

	var cookie  = Cookie.write('handle', 'SoccerStar23', {duration: 1, secure: true}); //save for a month

You could delete and re-create the cookie, but why? You can simply overwrite its value and options.

Reading a Cookie

	var handle = Cookie.read('handle');

Reading the cookie is just as easy as creating one!

Deleting a Cookie

if(logoff) { Cookie.dispose('handle'); }

When it's time to remove the cookie manually, the above code works every time.

So what would you use the MooTools Cookie for? How about saving text-size preferences? Also note that these cookies can be read by PHP too!

Recent Features

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    PHP / MooTools 1.2 Accordion Helper

    The MooTools Accordion plugin seems to be the plugin that people seem to have the most problems with. It's an awesome plugin, so I can see why so many people want to use it, but I think that may be part of the problem.

  • By
    Simple Image Lazy Load and Fade

    One of the quickest and easiest website performance optimizations is decreasing image loading.  That means a variety of things, including minifying images with tools like ImageOptim and TinyPNG, using data URIs and sprites, and lazy loading images.  It's a bit jarring when you're lazy loading images and they just...

Discussion

  1. Great timing! I was just reading the docs about this very topic. One question that I’ve had issues with. When I try to add both libraries Core and More builders I get errors in FireBug? I’ve tried downloading them in the same directory, but I still get issues with errors. Have you noticed this issue and if so how have you been able to work around it?

  2. @Seth: I’ve noticed the MooTools builder being shotty too. Here’s “core” and “more” together:

    http://davidwalsh.name/dw-content/moo1.2.js

  3. Kind of a dumb question…but would cookies work testing locally or would I have to test on a dev server?

  4. @Seth: Cookies are stored on the user’s machine by the browser so it’s doesn’t matter where your code is hosted. As long as your code exists in a page which you can see with a browser, and cookies are not disabled in your browser, they should work.

  5. @Seth, Evil: I know that PHP has problems with cookies on localhost, but I’m not sure about javascript.

  6. Alex

    Cookie.dispose doesn’t work in localhost (Windows Xampp) :P

  7. Make sure you include the path option as well to your domain root. If you don’t, Safari (on Mac) doesn’t believe the cookie is set. So, if you are checking for that cookie, you will not find it. At least, that was my experience. Let me know if I was doing something wrong. I didn’t have this problem with FireFox.

    Sample :

    // Try to read the screencast cookie
    var screencast = Cookie.read('screencast');
    
    if(screencast != 'true') {
        // Write the cookie so user won't be prompted again.
        var cookie  = Cookie.write('screencast', 'true', {duration: 180, domain: '.appbeacon.com', path: '/'}); //save for a month  
    
        // The cookie has not been set.  The user has not been shown the option to view screencast.
        alert('He has not seen it!');
    }
    
  8. Forgot to thank you for this. Once again, you’ve helped me solve a big problem. I was having trouble getting PHP to set my cookies. It was a mess trying to get it to work in my custom developed app and WordPress at same time.

    So, I resorted to Javascript cookies thanks to David and Mootools. Guess what? It was very easy and works great across the board.

    Thanks,
    Justin Noel

  9. Hi David,

    I’m write a class and I would like to store some data in a cookie. I’m having problems when I don’t implement Cookie and also when i do implement it.

    var cvStepSlider = new Class({
    
        Implements: [Options,Events,Chain,Cookie],
    
        //rest of the class
    });
    

    How do I use cookies within a class? Any suggestions?

  10. Doctor Star

    It is still need some programming knowdgle. Will be better methods to get work with.

  11. Hi-

    So I’ve got a very odd thing happening in FFox 3.5. I’m able to watch the cookie being set and then when I go to dispose it, it’s not working. If I don’t dispose it and try to set it again only 1 cookie appears, however, if I dispose it, Ffox retains the first cookie and then sets and new and identical one. Has anyone else seen this pattern and resolved it.

    On an aside, this also happens when I try to set/expire the cookies using PHP code as well as when I use the nsiCookieManager from within chrome.

  12. @david: Whether I can get the remaining expiration time of cookie?

  13. TitoChhabra

    Hello Everyone,
    Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. I.e. a cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. Cookies are part of the HTTP header…………….

    For more details please check out the following link…..
    http://mindstick.com/Articles/ae277d4f-30b8-4cc1-a6b8-b709ecc6e65d/?PHP%20Cookies

    Thanks !!!!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!