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
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    Retrieve Google Analytics Visits and PageViews with PHP

    Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? Anyways I check my website statistics more often than I should and...

  • By
    FileReader API

    As broadband speed continues to get faster, the web continues to be more media-centric.  Sometimes that can be good (Netflix, other streaming services), sometimes that can be bad (wanting to read a news article but it has an accompanying useless video with it).  And every social service does...

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!