You are currently viewing jQuery and Cookies: Storing User Data

jQuery and Cookies: Storing User Data

Cookies are small pieces of data stored on the user’s device by the web browser while they browse a website. They are commonly used for storing user preferences, session information, and other data that needs to persist across different pages or visits. Managing cookies effectively allows for a more personalized and seamless user experience.

jQuery, in combination with the js-cookie library, simplifies the process of setting, retrieving, and deleting cookies. In this article, we will explore how to use jQuery and js-cookie to manage cookies for storing user data. We will cover topics such as setting and retrieving cookies, deleting cookies, and practical use cases like remembering user preferences. Each section will include full executable code examples with detailed explanations.

Setting Up the Development Environment

Before we begin working with cookies, we need to set up our development environment. This includes including jQuery and the js-cookie library in our project and creating a basic HTML page to work with.

Including jQuery and js-cookie in Your Project

To include jQuery and js-cookie in your project, you can use a Content Delivery Network (CDN). This method ensures that you are always using the latest versions.

<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>

Adding the above script tags to the head section of your HTML file will include jQuery and js-cookie from a CDN.

Writing a Simple HTML Page

Next, let’s create a simple HTML page that we will use as the foundation for our cookie management examples. Create a new file named index.html and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery and Cookies</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
    <script src="script.js"></script>
</head>
<body>

    <h1>jQuery and Cookies</h1>

    <button id="setCookieButton">Set Cookie</button>
    <button id="getCookieButton">Get Cookie</button>
    <button id="deleteCookieButton">Delete Cookie</button>

    <div id="output"></div>

</body>
</html>

In this HTML file, we set up a basic structure that includes three buttons for setting, getting, and deleting cookies, and a div element to display output. The included CSS and JavaScript files (styles.css and script.js) will be used to style the page and add functionality, respectively.

Setting Cookies with jQuery

Introduction to Setting Cookies

Setting cookies involves creating key-value pairs that can be stored on the user’s device. These cookies can have optional attributes such as expiration time, path, and domain, which control their scope and lifespan.

Code Example: Setting a Simple Cookie

Create a new file named script.js and add the following code:

$(document).ready(function() {

    $('#setCookieButton').on('click', function() {

        Cookies.set('username', 'JohnDoe', { expires: 7 });
        $('#output').text('Cookie "username" set to "JohnDoe" with an expiration of 7 days.');

    });

});

In this code, we use $(document).ready() to ensure the DOM is fully loaded before executing our jQuery code. We attach a click event handler to the button with the ID setCookieButton. When the button is clicked, the Cookies.set method from the js-cookie library is used to set a cookie named username with the value JohnDoe that expires in 7 days. The output div is then updated to display a confirmation message.

Retrieving Cookies with jQuery

Introduction to Retrieving Cookies

Retrieving cookies involves reading the stored key-value pairs from the user’s device. This allows you to access user-specific data and preferences that have been previously saved.

Code Example: Getting Cookie Values

Update the script.js file with the following code:

$(document).ready(function() {

    $('#setCookieButton').on('click', function() {
        Cookies.set('username', 'JohnDoe', { expires: 7 });
        $('#output').text('Cookie "username" set to "JohnDoe" with an expiration of 7 days.');
    });

    $('#getCookieButton').on('click', function() {

        const username = Cookies.get('username');

        if (username) {
            $('#output').text('Cookie "username" has value: ' + username);
        } else {
            $('#output').text('Cookie "username" not found.');
        }

    });

});

In this code, we attach a click event handler to the button with the ID getCookieButton. When the button is clicked, the Cookies.get method from the js-cookie library is used to retrieve the value of the username cookie. If the cookie exists, its value is displayed in the output div. If the cookie does not exist, a message indicating that the cookie was not found is displayed.

Deleting Cookies with jQuery

Introduction to Deleting Cookies

Deleting cookies involves removing the stored key-value pairs from the user’s device. This is useful for clearing user-specific data and resetting preferences.

Code Example: Removing a Cookie

Update the script.js file with the following code:

$(document).ready(function() {

    $('#setCookieButton').on('click', function() {
        Cookies.set('username', 'JohnDoe', { expires: 7 });
        $('#output').text('Cookie "username" set to "JohnDoe" with an expiration of 7 days.');
    });

    $('#getCookieButton').on('click', function() {

        const username = Cookies.get('username');

        if (username) {
            $('#output').text('Cookie "username" has value: ' + username);
        } else {
            $('#output').text('Cookie "username" not found.');
        }

    });

    $('#deleteCookieButton').on('click', function() {
        Cookies.remove('username');
        $('#output').text('Cookie "username" has been deleted.');
    });

});

In this code, we attach a click event handler to the button with the ID deleteCookieButton. When the button is clicked, the Cookies.remove method from the js-cookie library is used to delete the username cookie. The output div is then updated to display a confirmation message that the cookie has been deleted.

Practical Use Cases

Remembering User Preferences

One practical use case for cookies is remembering user preferences, such as theme selection or language settings. By storing these preferences in cookies, you can provide a more personalized user experience.

Code Example: Storing and Retrieving User Preferences

Update the index.html file to include buttons for setting and retrieving user preferences:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery and Cookies</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
    <script src="script.js"></script>
</head>
<body>

    <h1>jQuery and Cookies</h1>

    <button id="setPreferenceButton">Set Dark Theme</button>
    <button id="getPreferenceButton">Get Theme Preference</button>
    <button id="deletePreferenceButton">Delete Theme Preference</button>

    <div id="output"></div>

</body>
</html>

Update the script.js file with the following code:

$(document).ready(function() {

    $('#setPreferenceButton').on('click', function() {
        Cookies.set('theme', 'dark', { expires: 7 });
        $('#output').text('Theme preference set to "dark" with an expiration of 7 days.');
        $('body').addClass('dark-theme');
    });

    $('#getPreferenceButton').on('click', function() {

        let theme = Cookies.get('theme');

        if (theme) {

            $('#output').text('Theme preference is: ' + theme);

            if (theme === 'dark') {
                $('body').addClass('dark-theme');
            } else {
                $('body').removeClass('dark-theme');
            }

        } else {
            $('#output').text('No theme preference found.');
        }

    });

    $('#deletePreferenceButton').on('click', function() {
        Cookies.remove('theme');
        $('#output').text('Theme preference has been deleted.');
        $('body').removeClass('dark-theme');
    });

    // Check and apply theme on page load
    let theme = Cookies.get('theme');

    if (theme === 'dark') {
        $('body').addClass('dark-theme');
    }

});

Update the styles.css file with the following code:

body {
    font-family: Arial, sans-serif;
    padding: 20px;
}

.dark-theme {
    background-color: #333;
    color: #fff;
}

In this example, we set up buttons for setting, getting, and deleting a theme preference cookie. When the “Set Dark Theme” button is clicked, a cookie named theme is set to dark with an expiration of 7 days. The body element is then given the dark-theme class to apply the dark theme styles. When the “Get Theme Preference” button is clicked, the value of the theme cookie is retrieved and used to apply the appropriate theme. The “Delete Theme Preference” button deletes the theme cookie and removes the dark theme styles. Additionally, we check and apply the theme preference on page load to ensure the user’s preference is applied consistently.

Conclusion

In this article, we explored how to use jQuery and the js-cookie library to manage cookies for storing user data. We covered setting, retrieving, and deleting cookies, and demonstrated practical use cases such as remembering user preferences. Each section included full executable code examples with detailed explanations.

The examples and concepts covered in this article provide a solid foundation for managing cookies with jQuery. However, there are many additional use cases and functionalities you can explore and implement to create a more personalized and user-friendly web experience. I encourage you to experiment further and expand the usage of cookies to suit your needs.

Additional Resources

To continue your journey with jQuery and web development, here are some additional resources that will help you expand your knowledge and skills:

  1. jQuery Documentation: The official jQuery documentation provides comprehensive information on using jQuery. jQuery Documentation
  2. js-cookie Documentation: The official documentation for the js-cookie library offers detailed guidance on managing cookies. js-cookie Documentation
  3. MDN Web Docs – Cookies: The MDN Web Docs provide an in-depth look at how cookies work and how to manage them in web development. MDN Web Docs – Cookies
  4. Online Tutorials and Courses: Websites like Codecademy, Udemy, and Coursera offer tutorials and courses on web development and jQuery, catering to different levels of expertise.
  5. Books: Books such as “jQuery in Action” by Bear Bibeault and Yehuda Katz provide in-depth insights and practical examples for web development.
  6. Community and Forums: Join online communities and forums like Stack Overflow, Reddit, and the jQuery mailing list to connect with other developers, ask questions, and share knowledge.
  7. Sample Projects and Open Source: Explore sample projects and open-source jQuery applications on GitHub to see how others have implemented various features and functionalities.

By leveraging these resources and continuously practicing, you’ll become proficient in using jQuery and cookies to develop dynamic and interactive web applications, improving your overall web development skills.

Leave a Reply