Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can actually modify specific CSS properties when the different modes are selected.

I am working with Angular 9. Any suggestions or solutions on how this can be achieved?

Answer №1

To implement this feature, you can utilize the power of BehaviourSubject from RXJS. Initially, set it to false and switch between light and dark mode by calling the next() method to update the behaviour subject. Make sure to subscribe to the BehaviourSubject variable on initialization to handle the response effectively.

For reference and detailed information, check out BehaviourSubject.

I have personally incorporated the dark mode feature in one of my projects showcased at telivic.com. You can find the implementation approach I used on that site. Hopefully, this solution will work well for you too.

addDark(){
    document.getElementById('nav').classList.add('dark');
    document.getElementById('box').style.backgroundColor = "#35363A";
     document.getElementsByTagName("BODY")[0].classList.add('dark');
     document.getElementById('modal').style.backgroundColor ="bisque";
     if(this.service.flag){
      document.getElementById('opt').classList.add('dark');
     }
     document.getElementById('gen').style.color="white";
     
  }
  removeDark(){
    document.getElementById('nav').classList.remove('dark');
    document.getElementById('box').style.backgroundColor = "#fff";
     document.getElementsByTagName("BODY")[0].classList.remove('dark');
     document.getElementById('modal').style.backgroundColor ="white";
     if(this.service.flag){
      document.getElementById('opt').classList.remove('dark');
     }
     document.getElementById('gen').style.color="black";
  }
  /*Binded my switch to this function I have used service so that user   dark/light mode preference can be processed in other pages also.*/
  darkMode(){
    this.dark = !this.dark;
    this.userService.setMode();
    if(this.dark){
      this.addDark();
    }else{
     this.removeDark();
      
    }
    
  }

Answer №2

To implement styled-components, consider the following code snippet:

import styled from 'styled-components'

const StyledComponent = styled.div`
    color: ${props => props.theme === `dark` ? `white` : `black`};
`

In your render method, utilize the component as shown below:

<StyledComponent theme={theme} />

Answer №3

To introduce a variable in your TypeScript file, simply add:

modeType: string;

This variable will toggle between 'dark' and 'light' based on the user's preference.

To apply CSS changes dynamically in your HTML, utilize ngClass or try this approach:

<div class="{{modeType == 'dark' ? 'dark-property': 'light-property'}}">

In your CSS stylesheet, define the styles as follows:

.dark-property{
 include your "dark" css properties
}

.light-property{
 include your "light" css properties
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

Trouble with triggering HTML5 FileReader() functions

I'm having trouble determining why neither readSuccess() nor readFailure() are being executed in the code snippet below: function readMyFile(){ var reader = new FileReader(); reader.onload = readSuccess; reader.onerror = readFailure; ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Switching between two distinct templateUrls within an Angular 6 component

When working with Angular 6, we are faced with having two different templates (.html) for each component, and the need to change them based on the deployment environment. We are currently exploring the best practices for accomplishing this task. Some pos ...

Convert a relative path to an absolute path using the file:// protocol

When I scrape a website with similar html content, I come across the following code: <a href="/pages/1></a> In addition to this, I have access to the window.location object which contains: origin:"http://www.example.org" This allows me to ...

utilize switchMap to terminate an HTTP request within an ngrx effect

Behold the ngrx effect in question: @Effect() throwError$: Observable<Action> = this.actions$.pipe( ofType<notificationActions.ErrorThrow>( notificationActions.ActionTypes.ThrowError ), tap(() => { this.store.dispa ...

Unable to modify the border radius of the carousel indicators in Bootstrap 5

Currently, I am working with the carousel component in Bootstrap 5.1. I have encountered an issue where I am unable to add border-radius to the carousel indicators, despite trying various methods. Even though the inspector shows that the indicators (HTML ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

Switch website address without redirecting via JavaScript

I am seeking information on how to update the URL without a full page reload, similar to the functionality seen on this website . When clicking on tabs, the URL changes seamlessly without refreshing the entire page. While some sources suggest that this m ...

Input for Shared Component with routerLink

I'm looking to develop a shared component featuring a button that, upon clicking, redirects the user to a specified location. I want the consumer of the component to be able to define the route. How can I make this happen? My current idea is to set t ...

Attempting to trigger CSS transitions using JavaScript will not be successful

I'm facing an issue where CSS transitions do not work as expected when triggered by JavaScript. let isSearchBarOpen = false; function toggleSearchBar() { if (isSearchBarOpen) { searchBar.style.display = "none"; } else { searchBar.sty ...

What is the process for extracting data from a canvas tag and why does it appear invisible on my browser?

The highlighted area in this image contains the HTML content and the red circle marks the section to be scraped The phone number can be found within the canvas tag. However, when trying to scrape the tag, it shows "Your browser does not support the HTML5 c ...

Using jQuery to refresh a div element

I am struggling with updating the "right" div in my jsp page using the script below. Despite being contained in a single file, the update does not seem to work. Any assistance is appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E ...

Having trouble finding the element during Selenium JavaScript testing

I need help testing a JavaScript script using Selenium, but I am running into an issue. I cannot seem to find a specific element that I want to click on. Here is a snippet of my JS code where I am trying to click on the Shipping option. I have tried us ...

Retrieving data from MongoDB for rendering on an HTML page

I have successfully inserted data into my MongoDB database, but I am facing issues with the "get" function to display this data on my HTML page. My current setup involves using Node.js with Express framework and Angular for front-end development and routi ...

The height of the footer element is gradually dwindling

Have you ever wondered why a footer element mysteriously shrinks in height when the browser window is resized? I attempted to create a fiddle with my code, but unfortunately, it's not replicable on JSFiddle so I won't be sharing it. This is how ...

Issue with function operation

Incorporating HTML code with Angular elements on the homepage of a PHP forum script has been challenging. I have inserted the PHP code into index.template.php as instructed, but unfortunately, nothing is being displayed. <?php /** * This function ...

Navigational elements, drawers, and flexible designs in Material-UI

I'm working on implementing a rechart in a component, but I've encountered an issue related to a flex tag. This is causing some problems as I don't have enough knowledge about CSS to find a workaround. In my nav style, I have display: flex, ...