📲 Download Our Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

How can create user preferences in JavaScript by storing the choice when the user clicks something, and then reloading it whenever the page is opened again

You can create user preferences in JavaScript by storing the choice when the user clicks something, and then reloading it whenever the page is opened again. The usual way is to use localStorage or cookies.

Here’s a step-by-step example:


Example: Save User Theme Preference (Dark/Light Mode)

HTML

<button id="themeToggle">Toggle Theme</button>
<p>Hello! This text will change theme.</p>

JavaScript

// Get saved preference (if any)
let userPref = localStorage.getItem("theme");
 document.cookie = "theme=light; path=/";

// Apply saved preference
if (userPref === "dark") {
  document.body.classList.add("dark");
  document.cookie = "theme=dark; path=/";
}

// Button click event
document.getElementById("themeToggle").addEventListener("click", () => {
  document.body.classList.toggle("dark");

  // Save user preference
  if (document.body.classList.contains("dark")) {
    localStorage.setItem("theme", "dark");
 document.cookie = "theme=dark; path=/";
  } else {
    localStorage.setItem("theme", "light");
 document.cookie = "theme=light; path=/";
  }
});

CSS

body {
  background: white;
  color: black;
}
body.dark {
  background: black;
  color: white;
}

How It Works

  1. When the user clicks the button → we toggle a CSS class.
  2. Save the preference in localStorage.
  3. Next time the user reloads, we restore the preference from localStorage.



Leave a Reply

AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes