YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Cookie Utility: Advanced Cookie Example

# Cookie Utility: Advanced Cookie Example

This example shows how to get, set, and remove cookies using the YUI Cookie utility.

### Note:

Keep an eye on the Logger console at right to view the log messages associated with this example.

Click the buttons to interact with the cookie:

## Advanced Cookie Example

This example consists of three buttons, each of which performs one of the basic cookie functions: getting a value, setting a value, and removing a value. The first button, "Get Value", retrieves the value of a cookie and displays it in an alert:

YAHOO.util.Event.on("yui-cookie-btn1", "click", function(){ var value = YAHOO.util.Cookie.get("example"); alert(value); YAHOO.log("Cookie 'example' has a value of '" + value + "'"); });

The second button, "Set Random Value", creates a random value and sets the cookie's value equal to it:

YAHOO.util.Event.on("yui-cookie-btn2", "click", function(){ var newValue = "yui" + Math.round(Math.random() * Math.PI * 1000); YAHOO.util.Cookie.set("example", newValue); YAHOO.log("Set cookie 'example' to '" + newValue + "'"); });

After clicking this button, you can go back and click "Get Value" to see the new value that was assigned to the cookie (you can also check the logger output).

The third button, "Remove Value", completely removes the cookie from the page:

YAHOO.util.Event.on("yui-cookie-btn3", "click", function(){ YAHOO.util.Cookie.remove("example"); YAHOO.log("Removed cookie 'example'."); });

When this button is clicked, it removes the cookie. If "Get Value" is clicked immediately afterwards, the value should be `null`.

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

### Cookie Utility Examples:

### More Cookie Utility Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings