Enabling Night Mode in an AngularJS Application

Currently, I am working on adapting an AngularJS project to support Dark Mode.

This application is a legacy system and quite intricate so I prefer not to duplicate the css file.

At present, the implementation involves monitoring a media query from the operating system and modifying some classes accordingly.

I have experimented with:

document.documentElement.setAttribute('data-theme', 'light');

as well as

angular.element(document.documentElement).setAttribute("data-theme", "dark");;

However, no visible changes are occurring.

My challenge lies in finding a way to alter the @media (prefers-color-scheme: dark) preference using JavaScript.

Is it possible to override the OS settings within the scope of Angular?

Answer №1

When attempting to manage the theme based on

@media (prefers-color-scheme: dark) {...}
, JavaScript cannot directly alter it. This aspect is controlled by the user-agent or potentially the operating system, such as macOS.

Take a look at these images generated from the same code but adjusted based on my OS theme preferences:

https://i.sstatic.net/kOhOX.png

https://i.sstatic.net/EAWdd.png

p {
background-color: white;
color: black;
}

@media (prefers-color-scheme: dark) {
 p {
 background-color: black;
 color: white;
 }
}
<p>Hello World!</p>


To have control over this using JavaScript, you must utilize CSS classes:

const app = document.getElementById("app");
const lightBtn = document.getElementById("light");
const darkBtn = document.getElementById("dark");

lightBtn.addEventListener("click", () => {
  app.classList.remove("dark");
  app.classList.add("light");
});

darkBtn.addEventListener("click", () => {
  app.classList.remove("light");
  app.classList.add("dark");
});
#app.light,
#app.light p,
#app.light button {
  background-color: white;
  color: black;
}

#app.dark,
#app.dark p,
#app.dark button {
  background-color: black;
  color: white;
}
<div id="app">
  <p>Hello World!</p>
  <button id="dark">Dark</button>
  <button id="light">Light</button>
</div>

Answer №2

To easily achieve this, it is recommended to utilize a database to store userSettingsTable colortheme information properties such as #000000 or #FFFFFF. This way, you can retrieve the information or update it whenever a user clicks on the color theme change, ensuring that the change is applied globally across all pages.

Below is an example of how you can implement this:

-------------Within HTML under the body tag---------

Firstly, declare the controller and app using ng-app="yourname" ng-controller="yourname"

<style ng-init=checkcolor()>
    body{
        background-color: {{colortheme}};
    }
</style>

---------Within the Controller------

$scope.changeTheme = function (colortheme){
if(colortheme == '#000'){
    $scope.colortheme = '#FFF';
      $http({
                method: "POST",
                url: "fetch_data_user_colortheme.php",
                data: {'user_profile':$scope.user_profile, 'color':$scope.colortheme,'action':'setcolor'}
            }).then(function(response) {
                console.log('changed to WHITE');
                console.log($scope.user_profile);
                console.log($scope.colortheme);
            })

} else if (colortheme == '#FFF') {
    $scope.colortheme = '#000';
      $http({
                method: "POST",
                url: "fetch_data_user_colortheme.php",
                data: {'user_profile':$scope.user_profile, 'color':$scope.colortheme,'action':'setcolor'}
            }).then(function(response) {
                console.log(response.data);
                console.log('changed to DARK');
                console.log($scope.user_profile);
                console.log($scope.colortheme);
            })
}
}

$scope.checkcolor = function (){
    $http({
                method: "POST",
                url: "fetch_data_user_colortheme.php",
                data: {'user_profile':$scope.user_profile, 'action':'getcolor'}
            }).then(function(response) {
                console.log(response.data);
                $scope.colortheme = response.data.toString();
                console.log($scope.colortheme.toString());
            })
}

-----------Within the model/backend e.g., PHP--------------

<?php

//fetch_data_user_colortheme.php

$connect = new PDO("mysql:host=localhost;dbname=cinema_db", "root", "");

$form_data = json_decode(file_get_contents("php://input"));

if ($form_data->action == 'getcolor') {
    $query = "SELECT colortheme FROM usersettingstable WHERE user_fk='".$form_data->user_profile."'";

    $statement = $connect->prepare($query);

    if ($statement->execute()) {
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row['colortheme'];
        }
    }
}
elseif ($form_data->action == 'setcolor') {
    $query = "
    UPDATE usersettingstable 
    SET user_fk='".$form_data->user_profile."', colortheme='".$form_data->color."'
    ";
    $statement = $connect->prepare($query);
    if($statement->execute())
    {
       
    }
    $query = "SELECT colortheme FROM usersettingstable 
              WHERE user_fk='".$form_data->user_profile."'";
    $statement = $connect->prepare($query);
    if ($statement->execute()) {
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $row['colortheme'];
    }
  }
}
 echo json_encode($data);

?>

Additionally, ensure to include the checkcolor() function in other pages as well by calling it within a controller using ng-init="checkcolor()". This will help maintain the color settings across all pages, and you may need to make adjustments accordingly.

             $scope.checkcolor = function (){
                $http({
                method: "POST",
                url: "fetch_data_user_colortheme.php",
                data: {'user_profile':$scope.user_profile, 
               'action':'getcolor'}
            }).then(function(response) {
                console.log(response.data);
                $scope.colortheme = response.data.toString();
                console.log($scope.colortheme.toString());
               document.body.style.background = $scope.colortheme;

            })
          }

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

packages have gone AWOL in the Bitbucket pipeline

Hello everyone. I am currently working on setting up a pipeline for my nextjs-project and I've encountered a problem. I have a specific function for generating buildId # scripts/generate-build-id.js const nextBuildId = require('next-build-id&ap ...

Can you help me with compiling Twitter Bootstrap 3.0 on my Windows 8?

Can anyone guide me on compiling Twitter Bootstrap using Less on a Windows machine? I tried following a tutorial but ran into issues with installing lessc (it was not in the npm registry). Also, the tutorial was for BS2 and not 3.0 which made me skeptical ...

Traversing a multidimensional array with jQuery

In my quest to iterate through a multidimensional array, I encountered the need to remove the class "list" from the divs within the array. However, there could be multiple divs with this class on my site. My initial approach involved using two for-loops, ...

View and Element UI combined for PDF previews prior to file uploading

I am currently utilizing Vue along with the element UI to enable file upload functionality, and I am also incorporating the pdfvuer node module. The uploaded files are ultimately being sent to Amazon S3. My goal is to allow users to preview the file befor ...

Two simultaneous controller commands

There seems to be an issue with the controller being called twice. I am working with a sample app and have noticed that when I click on "Show Order" in Chromium console, the message "Call ShowOrdersController" appears as expected. However, when I click on ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

The challenge of handling multiple save conflicts in asynchronous Mongoose operations

My Node/Mongoose/Socket.io setup is presenting a challenging logic issue. Imagine a scenario where the Server model is frequently accessed and updated simultaneously in my application. db.Server.findOne({_id: reference.server}).exec(function(error, se ...

How can you use jQuery to transform a H3 tag into a clickable link?

To transform the h3 tag into a clickable link with jQuery and set the href attribute, while preserving the H3 styling and adding an anchor tag, you can use the following code as an example: Click Here ...

Utilizing AJAX to showcase an HTML popup

I am currently working on a project to create an HTML page that will display another HTML file in an alert when a button is pressed. However, I am facing an issue where the content is not being displayed as expected. <html> <head> ...

React - Next Blog: Issue with empty lines displaying on the browser

Currently, I am developing a blog that retrieves data from Mongo Atlas. The blog is built using Next.js version 9.5.4 and is hosted on Vercel. The blog page utilizes static props and regeneration. The data is fetched in JSON format and then stringified fo ...

Expanding the size of a text area input within a form using CSS and

How can I adjust the size of the text area in the Comment section to match the full width of the section, starting from the beginning instead of the middle? You can find the code here. HTML <body bgcolor="#00BCD4"> <div> <h1>Co ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...

Restricting the webkit-overflow-scrolling functionality is essential

I am facing an issue with a div that needs horizontal scrolling. It works fine without using -webkit-overflow-scrolling, but on the iPhone, I don't get the native bouncing effect. The scrolling is only happening horizontally when it should also be pos ...

Respond to onClientClick based on the button choice made by the user

In my code, there is an OnClientClick event set up like this: OnClientClick="return getErrors();". This function contains the following body: function getErrors() { var errorString = "some errors"; return $('<div id="dialog-message" title= ...

The VUE project I'm working on seems to be having compatibility issues with the Bootstrap modal in V

I added bootstrap using npm and inserted the code from bootstrap into my project, but it's not functioning correctly. I've spent an hour trying to troubleshoot, but still no luck. Here is the code snippet: <template> <div> <! ...

JavaScript: Determine the wild decimal value produced by subtracting two decimal numbers

In the process of creating a service price tracking bot, I encountered an issue with displaying price decreases. Here is an example of what it currently looks like: Service price decreased from 0.10 to 0.05 If you buy right now, you could save <x> ...

Guide to building a simple AngularJS webpage to fetch and display RESTful JSON data

I am in the process of developing a simple webpage that displays data retrieved from http://rest-service.guides.spring.io/greeting. The JSON output looks like this: {"id":2273,"content":"Hello, World!"} This is the HTML code I am using: <body ng-app ...

Tips for incorporating real-time information into a highchart graph?

I'm currently working on a Highchart that utilizes AJAX and jQuery for receiving JSON data. However, I've noticed that the points on my chart only appear when I hover over it, and even then they all seem to be clustered at the top of the chart. I ...

establish the reliance on field w

I want to create a dependency between two fields. The selectbox contains a list of options. If the first or fifth option is selected in the dropdownbox, apply the class "selectboxlist". Then I would like to set the value '-1' in the second ...

Place a picture within a specified View

I am encountering an issue with my profile image in the header component. The source of the image is coming from the database as a string array. However, when I fetch the user picture from the database, it appears slightly cut off from the top, giving the ...