Cookies are useful for a number of reasons. Their classic use is to store form information such as usernames, emails, etc. You can set cookies using jQuery just as easy as you can with PHP or any other language.

Working with Cookies and jQuery

jQuery allows you to set cookies using any one of their methods. Let’s use the .click() method to set a cookie. Working example: Click on the cookie image below to set a cookie:

Set a Cookie using jQuery

The jQuery Cookie Plugin

If you’re going to be working with jQuery to set cookies then you’re going to want to use the jQuery Cookie Plugin. This plugin is easy to work with and very lightweight.

Set the Cookie

We’re going to use the jQuery .click() method to set a cookie when the user clicks a button. Here’s the code I used for the demo cookie:

Let’s get a bit more fancy. Suppose you have a footer popup panel, similar to the one I just did on cheapsally.com that holds an advertisement. Most likely you’re going to want to set a cookie so it doesn’t bombard the user when they click it and continue browsing your website.

What’s going on here is first checking to whether the cookie exists on the user’s computer. If it does then the panel will remain hidden. If not, it slides up. When a user clicks the close button in the panel it sets the cookie. Demo coming soon!

How to Delete the Cookies

To delete the cookie simply pass a null value to it. Please remember you must use the same path and domain used when the cookie was set.

How to Alert the Cookie Values

Using an alert to display your cookie value’s is a helpful way to debug your code:

Use PHP functions for Cookie Values

With PHP you can set a number of values and make cookies even more userful. Check out this example using some of WordPress’ functions:

Devin Walker is a San Diego-based WordPress Developer and enthusiast. He is the author of several popular and highly-rated WordPress themes and plugins. In his free time he enjoys playing Golf and traveling.

Follow
Devin

Is your WordPress Running Slow?

Milliseconds are money. Website speed is extremely important. We highly recommend WP Engine. Why? Because they make a sluggish WP site fast, support is great and they have excellent uptime.

WP Engine Logo