Sling Academy
Home/JavaScript/Saving User Preferences and Applying Them to the DOM with JavaScript

Saving User Preferences and Applying Them to the DOM with JavaScript

Last updated: December 12, 2024

Saving user preferences on a webpage and applying them to the Document Object Model (DOM) can significantly enhance user experience by making the web application feel more personalized. In this article, we'll explore how to save preferences such as theme settings, layout options, or language selection, and then apply these preferences using JavaScript.

Understanding the Basics

The first step in saving user preferences is to understand the local storage capabilities of web browsers. Web browsers support a localStorage object that allows developers to store data locally within the user's browser. This data is persistent, meaning it does not expire and will remain until explicitly removed.

Using Local Storage in JavaScript

The localStorage object allows you to store simple key-value pairs. Here is how you can use it:

// Store user preferences
localStorage.setItem('theme', 'dark');

// Retrieve user preferences
const userTheme = localStorage.getItem('theme');

In this example, we save a user's theme preference to local storage using setItem. Loading the value back is done via getItem. It's important to handle the absence of a value gracefully, as shown below:

// Check if a theme is saved
const savedTheme = localStorage.getItem('theme') || 'light'; // Default is 'light'

Applying Preferences to the DOM

Once you have the preference data, applying it to the DOM lets you alter the user's experience based on their saved settings, like changing themes or adjusting language. Here's how you might apply a saved theme:

// Retrieve saved theme
const theme = localStorage.getItem('theme') || 'light';

// Apply the theme by altering the DOM
function applyTheme(theme) {
    document.body.className = theme;
}

applyTheme(theme);

With this script, the saved theme class (either 'light' or 'dark') is applied to the body element, which can be styled in CSS.

Example: Theme Toggle

Let's create a simple example where a user can toggle between a light and dark theme. The choice will be saved to local storage and applied whenever the user revisits the page.

<button id="theme-toggle">Toggle Theme</button>
document.getElementById('theme-toggle').addEventListener('click', () => {
    const currentTheme = document.body.className;
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    document.body.className = newTheme;
    localStorage.setItem('theme', newTheme);
});

In this code, clicking the toggle button changes the body's class and stores the current preference in the local storage. Next time the user access the site, the saved theme will be retrieved and applied, maintaining the user’s preference.

Considerations and Best Practices

  • Always set defaults for your preferences to ensure a consistent user experience.
  • Consider using more sophisticated storage options, like IndexedDB, for complex data.
  • Offer clear and easy-to-use interface elements for users to change their preferences.

With what we've learned, developers can enhance user satisfaction by tailoring the interface to individual preferences. This not only improves the aesthetic and functional engagement of your web application, but also encourages repeat visits through a personalized web experience.

Previous Article: Detecting Touch vs Click Events for Mobile-Friendly Pages in JavaScript

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration