Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Saving user preferences using localStorage and jQuery

Posted on April 2, 2025April 2, 2025 by Zubair Shaik

Loading

Storing user preferences enhances the user experience by preserving individual settings across sessions. This guide will walk you through implementing user preference storage using localStorage and jQuery, covering the following aspects:

  1. Understanding localStorage and Its Advantages
  2. Setting Up the HTML Structure
  3. Integrating jQuery
  4. Implementing Theme Selection and Persistence
  5. Handling Form Input Persistence
  6. Managing Complex Preferences with Objects
  7. Ensuring Browser Compatibility
  8. Best Practices and Security Considerations

1. Understanding localStorage and Its Advantages

localStorage is a Web Storage API that allows storing key-value pairs in a user’s browser with no expiration time, ensuring data persists even after the browser is closed and reopened. This makes it ideal for saving user preferences like theme settings, language choices, and other customizable options. Unlike cookies, localStorage offers a larger storage capacity and does not send data with every server request, enhancing performance. citeturn0search6

Key Characteristics of localStorage:

  • Persistence: Data remains stored across browser sessions until explicitly deleted.
  • Capacity: Typically allows up to 5MB of data per origin, significantly more than cookies.
  • Scope: Accessible only within the domain that stored it, ensuring data privacy.

2. Setting Up the HTML Structure

Begin by creating a simple HTML structure that includes elements for user preferences. For example, a theme selector and a sample text area:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Preferences</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="preferences">
        <label for="theme">Choose Theme:</label>
        <select id="theme">
            <option value="light">Light</option>
            <option value="dark">Dark</option>
        </select>
    </div>
    <div id="content">
        <p>This is a sample content area.</p>
    </div>
    <script src="jquery.min.js"></script>
    <script src="scripts.js"></script>
</body>
</html>

In this setup:

  • A <select> element allows users to choose between ‘Light’ and ‘Dark’ themes.
  • A <div> with the ID content represents the main content area whose appearance will change based on the selected theme.

3. Integrating jQuery

To simplify DOM manipulation and event handling, include jQuery in your project. Download the jQuery library and link it in your HTML file as shown above. citeturn0search5

4. Implementing Theme Selection and Persistence

To enable theme selection and ensure the chosen theme persists across sessions:

  1. Apply the Selected Theme: Create a styles.css file to define styles for both themes: /* styles.css */ body.light-theme { background-color: white; color: black; } body.dark-theme { background-color: black; color: white; }
  2. Save and Retrieve Theme Preference Using localStorage: In your scripts.js file, add the following code: $(document).ready(function() { // Retrieve the saved theme from localStorage var savedTheme = localStorage.getItem('theme') || 'light'; $('body').addClass(savedTheme + '-theme'); $('#theme').val(savedTheme); // Change theme on selection $('#theme').on('change', function() { var selectedTheme = $(this).val(); $('body').removeClass('light-theme dark-theme').addClass(selectedTheme + '-theme'); localStorage.setItem('theme', selectedTheme); }); }); Explanation:
    • On document ready, the script retrieves the saved theme from localStorage. If no theme is saved, it defaults to ‘light’.
    • The retrieved theme is applied to the <body> element by adding the corresponding class.
    • The <select> element’s value is set to the saved theme.
    • An event listener is added to the <select> element to detect changes. When a new theme is selected:
      • The existing theme classes are removed from the <body>.
      • The new theme class is added.
      • The selected theme is saved to localStorage.
    This approach ensures that the user’s theme preference is applied immediately and persists across sessions. citeturn0search2

5. Handling Form Input Persistence

To enhance user experience, you can save form inputs so that users don’t lose their data upon page reloads or accidental navigations. Here’s how to implement this for text inputs:

  1. HTML Form Setup: <form id="userForm"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <button type="submit">Submit</button> </form>
  2. JavaScript to Save and Load Form Data: In your scripts.js file: $(document).ready(function() { // Load saved form data $('#userForm input').each(function() { var inputName = $(this).attr('name'); var savedValue = localStorage.getItem(inputName); if (savedValue) { $(this).val(savedValue); } }); // Save form data on input change $('#userForm input').on('input', function() { var inputName = $(this).attr('name'); var inputValue = $(this).val(); localStorage.setItem(inputName, inputValue); }); // Optional: Clear localStorage on form submit $('#userForm').
Posted Under jQueryAngular localStorage services browser storage solutions caching strategies with localStorage client-side storage cross-browser compatibility data expiration strategies data persistence techniques data serialization for storage debugging localStorage issues detecting localStorage support event handling with jQuery and localStorage fallback mechanisms for localStorage GDPR compliance and localStorage handling JSON in localStorage handling sensitive data in localStorage HTML5 storage implementing dark mode with localStorage integrating localStorage with frameworks JavaScript data persistence jQuery localStorage integration jQuery storage plugins localStorage localStorage and A/B testing localStorage and accessibility considerations localStorage and adaptive learning localStorage and advertising preferences localStorage and aerospace industry localStorage and affiliate marketing localStorage and afforestation localStorage and age verification localStorage and agroforestry localStorage and analytics data localStorage and arbitration localStorage and artificial intelligence localStorage and audio streaming localStorage and augmented reality localStorage and automotive applications localStorage and biodiversity localStorage and biometric authentication localStorage and blockchain technology localStorage and blogging platforms localStorage and board of directors localStorage and brain-computer interfaces localStorage and browser extensions localStorage and carbon footprint localStorage and case law localStorage and case studies localStorage and chatbots localStorage and circular economy localStorage and climate change localStorage and clinical trials localStorage and community gardens localStorage and compliance localStorage and compliance auditing localStorage and conservation localStorage and content management systems localStorage and content moderation localStorage and content security policy localStorage and contests localStorage and contracts localStorage and conversion optimization localStorage and copyright protection localStorage and corporate governance localStorage and corporate social responsibility localStorage and cross-origin resource sharing localStorage and crowdfunding platforms localStorage and cryptocurrency wallets localStorage and customer relationship management localStorage and cybersecurity localStorage and data compression localStorage and data visualization localStorage and deep learning localStorage and defense systems localStorage and deforestation localStorage and desertification localStorage and digital asset management localStorage and digital forensics localStorage and disaster management localStorage and dispute resolution localStorage and donation management localStorage and drug development localStorage and e-commerce applications localStorage and e-learning platforms localStorage and educational platforms localStorage and emergency services localStorage and energy efficiency localStorage and enterprise resource planning localStorage and environmental impact localStorage and environmental monitoring localStorage and ethical hacking localStorage and ethics localStorage and event planning tools localStorage and facial recognition localStorage and financial data localStorage and fisheries management localStorage and fitness tracking localStorage and food delivery services localStorage and food security localStorage and form validation localStorage and freelancing platforms localStorage and gamification localStorage and gaming applications localStorage and genetic data localStorage and geolocation data localStorage and gesture control localStorage and gig economy localStorage and global warming localStorage and government services localStorage and habitat restoration localStorage and healthcare access localStorage and healthcare applications localStorage and hotel management systems localStorage and human resources management localStorage and identity management localStorage and iframe communication localStorage and image caching localStorage and incident response localStorage and IndexedDB comparison localStorage and influencer marketing localStorage and intellectual property localStorage and Internet of Things localStorage and inventory tracking localStorage and job boards localStorage and language translation localStorage and law enforcement localStorage and legal considerations localStorage and legal research localStorage and licensing localStorage and litigation localStorage and loyalty programs localStorage and machine learning models localStorage and malware analysis localStorage and marine life localStorage and mediation localStorage and medical research localStorage and mental health localStorage and military applications localStorage and mobile web apps localStorage and multimedia content localStorage and multivariate testing localStorage and natural language processing localStorage and negotiations localStorage and neural networks localStorage and news websites localStorage and non-profit organizations localStorage and nutrition localStorage and ocean pollution localStorage and online forums localStorage and organic farming localStorage and parental controls localStorage and patents localStorage and penetration testing localStorage and performance metrics localStorage and permaculture localStorage and personalized content localStorage and personalized medicine localStorage and pharmaceuticals localStorage and phishing prevention localStorage and plastic waste localStorage and point of sale systems localStorage and polls localStorage and portfolio management localStorage and privacy concerns localStorage and progressive web apps localStorage and project management applications localStorage and public health localStorage and public transportation systems localStorage and push notifications localStorage and quantum computing localStorage and quizzes localStorage and real-time applications localStorage and recommendation systems localStorage and recruitment platforms localStorage and recycling localStorage and reforestation localStorage and regulations localStorage and remote work tools localStorage and renewable energy localStorage and retention strategies localStorage and rewards systems localStorage and ride-sharing applications localStorage and risk management localStorage and royalties localStorage and scientific research localStorage and sentiment analysis localStorage and server synchronization localStorage and service workers localStorage and shareholders localStorage and single-page applications localStorage and smart cities localStorage and smart devices localStorage and social media platforms localStorage and social proof localStorage and soil erosion localStorage and space exploration localStorage and spam filtering localStorage and speech synthesis localStorage and stakeholders localStorage and statutes localStorage and supply chain management localStorage and surveys localStorage and sustainability localStorage and sustainable agriculture localStorage and telemedicine localStorage and testimonials localStorage and third-party scripts localStorage and threat intelligence localStorage and ticketing systems localStorage and trademarks localStorage and travel booking platforms localStorage and urban gardening localStorage and urban planning localStorage and user engagement localStorage and user feedback localStorage and user tracking localStorage and user-generated content localStorage and vaccine distribution localStorage and video buffering localStorage and virtual assistants localStorage and virtual classrooms localStorage and virtual reality localStorage and voice recognition localStorage and vulnerability assessment localStorage and waste management localStorage and water conservation localStorage and wearable health devices localStorage and wearables localStorage and web security localStorage and wellness localStorage and wildlife protection localStorage API methods localStorage best practices localStorage cleanup strategies localStorage data backup strategies localStorage data migration localStorage encryption methods localStorage limitations localStorage polyfills localStorage quota management localStorage security localStorage tutorial localStorage vs cookies managing localStorage in React managing user sessions monitoring localStorage usage Offline Data Storage performance optimization with localStorage retrieving data from localStorage saving form data sessionStorage storing complex objects storing user language preferences storing user preferences synchronizing localStorage across tabs theme preference storage user authentication tokens storage user consent for localStorage usage user settings management Vue.js localStorage integration web application state web development storage options web storage api

Post navigation

Trying to set a state variable outside the component function
Passing a function as a prop but forgetting to bind it in class components

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions