Rapid processing of JavaScript upon page load

I recently implemented a dark mode feature on my WordPress site.

Here are the four modes I included:

1- Automatically based on user's system settings

2- Light mode

3- Semi-lit mode

4- Dark mode

The implementation is in place and functioning perfectly.

However, there is an issue with the code being inactive upon page load.

Currently, after loading the page, the code remains inactive. To activate it, users have to manually click on one of the mode options. I would like the code to be active regardless of the initial state of the page.

let bodyMode = document.querySelector("#pageMode");
let SystemMode = document.querySelector(".pageSystemMode");
let DarkMode = document.querySelector(".pageDarkMode");
let LightMode = document.querySelector(".pageLightMode");
let HalfLitMode = document.querySelector(".pageHalfLitMode");

SystemMode.addEventListener("click", function () {

    const UserMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

    if (UserMode) {
        $(bodyMode).addClass("bodyDark");
        $(bodyMode).removeClass("bodyLight bodyHalfLit");
    } else {
        $(bodyMode).removeClass("bodyLight bodyDark bodyHalfLit");
    }

});

DarkMode.addEventListener("click", function () {
    $(bodyMode).addClass("bodyDark");
    $(bodyMode).removeClass("bodyHalfLit");
});

HalfLitMode.addEventListener("click", function () {
    $(bodyMode).addClass("bodyHalfLit");
    $(bodyMode).removeClass("bodyDark");
});

LightMode.addEventListener("click", function () {
    $(bodyMode).addClass("bodyLight");
    $(bodyMode).removeClass("bodyDark bodyHalfLit");
});
.main-selectMode {
  position: absolute;
  top: 20%;
  left: 2%;
}

a.main-btn {
  font-weight: 900;
  padding: 10px;
  direction: rtl;
  color: #fff;
  background: #2512b0;
  border: none;
  box-shadow: 0 0 4px #000, 0 0 4px #fff;
}



a.main-btn:hover,
.btn-secondary:hover,
.btn-check:checked+.btn,
.btn.active,
.btn.show,
.btn:first-child:active,
:not(.btn-check)+.btn:active {
  color: #fff;
  background: #2512b0;
  border: none;
  box-shadow: 0 0 4px #000, 0 0 4px #fff;
}

.main-btn::before {
  margin: 0 7px 0 10px;
}

.main-btn::after {
...

</body>

Answer №1

Create a function to set the theme and execute it either immediately or by clicking:

function setTheme(){

        const userPrefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    
        if (userPrefersDarkMode) {
            $(body).addClass("darkTheme");
            $(body).removeClass("lightTheme halfLitTheme");
        } else {
            $(body).removeClass("lightTheme darkTheme halfLitTheme");
        }
}

//Click event listener

SystemMode.addEventListener("click", function () {
   setTheme();
});


//Immediate execution:
setTheme();

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

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...

The encoding of Node.js using npm

Looking to install the validate .json file below using npm: { "name": "node-todo", "version": "0.0.0", "description": "Simple todo application", "main": "server.js", "dependencies": { "express": "~3.4.4", "mongoose": "~ ...

Using `encodeURIComponent` to encode a URL does not function properly when used with a form action

After experimenting with the encodeURI function in conjunction with a form, I discovered an interesting behavior. I used encodeURI to encode a URL. <html> <head> </head> <body> <form id="form"> </form> <button id="bu ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

Searching for a comprehensive guide to web-related terminology that is widely accepted

Constantly immersing myself in studying the languages I am familiar with and exploring new development concepts and languages is a regular practice for me. When it comes to books, O'Reilly is my go-to choice, but when it comes to online resources, I&a ...

Guide to verifying a Django form with AngularJs

I have a very simple form with 1 field and a submit button. I want to implement validation such that the submit button is disabled when the field is empty and enabled when it is not. I am trying to achieve this dynamically using AngularJs but seem to be mi ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Is there a way to create a footer similar to this one?

I need to create a footer, but I'm struggling with placing a circle at the top half of the footer like this. Even though I can create a footer, I still encounter some issues. This is the code I have right now: .Footer { position: fixed; left: ...

Error message: The method app.get() is invalid as it is not a

I'm having trouble using Express in a prototype function ioServer() { } module.exports = ioServer; ioServer.prototype.start = function() { var app = require('express') var http = require('http').Server(app) ...

When attempting to showcase an MUI icon that was imported, I encounter the following issues: Invalid hook call and the <ForwardRef(SvgIcon)> component

Encountering issues while trying to display an imported MUI icon leads to the following errors: Error: https://i.stack.imgur.com/USdEx.png Sample Code: import React from 'react' import ThreeDRotation from '@mui/icons-material/ThreeDRotati ...

Add a variety of parameters to the URL in order to make an AJAX request

I want to dynamically add values from checked checkboxes to a URL for use in an AJAX call. I only want these values to be added to the URL if the checkbox is checked. If a user checks and then unchecks, I do not want that value included in the URL. Below ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

Creating a dual-direction infinite scroll effect with CSS through mouse dragging

I'm currently working on implementing an infinite scroll component for a project. After consulting this tutorial, I've encountered an issue. It seems that I can only achieve infinite scroll in one direction. Whenever I add elements to the leftmo ...

Inaccuracies arise when trying to interpret a JSON string as an object

I have tried various solutions found on stack overflow, but none of them seem to work for me. I am attempting to call an asmx web service using jQuery. Below is my code: <script type="text/javascript"> $(document).ready(function () { ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

Enhancing Your Website with WordPress Customizer API: Introducing Kirki's Repeater Image Feature

Allow me to clarify this situation as thoroughly as I can. To begin with, I am utilizing a toolkit known as Kirki to enhance the WordPress Customizer API Within my theme, there is a section that features a 4-column layout of services, each accompanied by ...