#

# Example: Advanced Cookie Example

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

Click the buttons to interact with the cookie:

## Description

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 logs it:

    Y.one("#yui-cookie-btn1").on("click", function () {
        var value = Y.Cookie.get("example");
        Y.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:

    Y.one("#yui-cookie-btn2").on("click", function () {
        var newValue = "yui" + Math.round(Math.random() * Math.PI * 1000);
        Y.Cookie.set("example", newValue);
        Y.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:

    Y.one("#yui-cookie-btn3").on("click", function () {
        Y.Cookie.remove("example");
        Y.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`.

## Complete Example Source

    <p>Click the buttons to interact with the cookie:</p>

    <p>
    <input type="button" value="Get Value" id="yui-cookie-btn1">
    <input type="button" value="Set Random Value" id="yui-cookie-btn2">
    <input type="button" value="Remove Value" id="yui-cookie-btn3">
    </p>

    <pre id="results"></pre>

    <script>
    YUI().use('cookie', 'node', function (Y) {

        var pre = Y.one('#results'),
            log = function(str) {
                pre.append(str + '\n<br>');
            }

        Y.one("#yui-cookie-btn1").on("click", function () {
            var value = Y.Cookie.get("example");
            log("Cookie 'example' has a value of '" + value + "'");
        });

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

        Y.one("#yui-cookie-btn3").on("click", function () {
            Y.Cookie.remove("example");
            log("Removed cookie 'example'.");
        });

    });
    </script>