- MooTools 1.3 Cookbook
- Jay Larry G. Johnston
- 305字
- 2021-04-02 19:07:10
Creating a welcome message based on a JavaScript cookie
Display an Alert "Hello, [Name]" to our visitor, with a cookie that was set some time earlier.
How to do it...
The MooTools Cookie class makes it surprisingly easy to create, read, access, and purge cookies. The method Cookie.write()
takes a key, a value, and optionally an object of options; for instance, the option duration
takes an integer that represents the number of days a cookie should be kept by a visitor. Cookie.read(),
terribly simple in syntax, takes the key of the cookie value that we wish to read. If empty the value is, it returns false. And, of course, we could not properly purge any cookie without the handy Cookie.dispose()
whose first parameter is identical to read()
and second parameter will merge the passed object of options with the existing cookie object options.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <form action="" method="get"> <span id="set_cookie"> Please enter your username: <input id="my_cookie_value" type="text"/> <input id="my_cookie_write" type="button" value="Write Cookie"/> </span> <input id="my_cookie_read" type="button" value="Read Cookie"/> </form> <script type="text/javascript"> // my_cookie_val will have the value of the key var my_cookie_val = Cookie.read('users_name'); if (!my_cookie_val) $('my_cookie_read').setStyle('visibility','hidden'); else $('my_cookie_value').set('value', my_cookie_val); $('my_cookie_write').addEvent('click', function() { // set a length of days for the cookie to be kept // by the user var days = 1; // get the username given by the user var my_cookie_val = $('my_cookie_value').get('value'); // my_cookie_obj will have the options, key, // and the value in it var my_cookie_obj = Cookie.write('users_name', my_cookie_val, {duration: days}); // my_cookie_read now has something to read $('my_cookie_read').setStyle('visibility','visible'); $('set_cookie').setStyle('visibility','hidden'); }); $('my_cookie_read').addEvent('click', function() { var my_cookie_val = Cookie.read('users_name'); alert('Hello '+my_cookie_val); }); </script>
How it works...
Our final recipe in this chapter uses Element.set(), Element.get()
, and Element.setStyle()
to read and alter properties and style properties of HTML elements on the page, real-time. Visible, as well, are two useful examples of adding event listeners with Element.addEvent()
.
Tip
Remember, you can switch paddles midstream because paddles float. Hoard your cookies! Okay, just kidding, share the cookies, we have more.