Troubleshooting the dark mode toggle feature on WordPress after converting from Webflow: JavaScript unable to locate CSS variables

Having an issue with my WordPress site and custom JavaScript. The code is loaded into the site using this script tag on line 16 in the head-section:

<script tr-color-vars="text,background,button-background,button-text,background-50,nav-menu-link,toggle-bg,toggle-offset"
duration="0.5" ease="power1.out"
src="https://cdn.jsdelivr.net/gh/timothydesign/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="374454455e47434477410619071905">[email protected]</a>/dark-mode-toggle.js">

The 'tr-color-vars' lists the variables to change between light and dark-mode. The 'src=' calls the cdn-hosted code.

In my Webflow website where I converted the theme from, the toggle works fine.

On the WordPress site, the script returns an error message:

No variables found matching the tr-color-vars attribute value

However, the variables are there.

Why can't the js-code find the variables? Any help would be appreciated.

live webflow site (working example)

link of wordpress site (toggle issue)

I obtained this code and how-to from Timothy Ricks on YouTube: Tutorial

JavaScript code:

/**
 * Dark Mode Toggle 1.0.2
 * Copyright 2023 Timothy Ricks
 * Released under the MIT License
 * Released on: November 28, 2023
 */

function colorModeToggle() {
  function attr(defaultVal, attrVal) {
    const defaultValType = typeof defaultVal;
    if (typeof attrVal !== "string" || attrVal.trim() === "") return defaultVal;
    if (attrVal === "true" && defaultValType === "boolean") return true;
    if (attrVal === "false" && defaultValType === "boolean") return false;
    if (isNaN(attrVal) && defaultValType === "string") return attrVal;
    if (!isNaN(attrVal) && defaultValType === "number") return +attrVal;
    return defaultVal;
  }

  const htmlElement = document.documentElement;
  const computed = getComputedStyle(htmlElement);
  let toggleEl;
  let togglePressed = "false";

  const scriptTag = document.querySelector("[tr-color-vars]");
  if (!scriptTag) {
    console.warn("Script tag with tr-color-vars attribute not found");
    return;
  }

  let colorModeDuration = attr(0.5, scriptTag.getAttribute("duration"));
  let colorModeEase = attr("power1.out", scriptTag.getAttribute("ease"));

  const cssVariables = scriptTag.getAttribute("tr-color-vars");
  if (!cssVariables.length) {
    console.warn("Value of tr-color-vars attribute not found");
    return;
  }

  let lightColors = {};
  let darkColors = {};
  cssVariables.split(",").forEach(function (item) {
    let lightValue = computed.getPropertyValue(`--color--${item}`);
    let darkValue = computed.getPropertyValue(`--dark--${item}`);
    if (lightValue.length) {
      if (!darkValue.length) darkValue = lightValue;
      lightColors[`--color--${item}`] = lightValue;
      darkColors[`--color--${item}`] = darkValue;
    }
  });

  if (!Object.keys(lightColors).length) {
    console.warn("No variables found matching tr-color-vars attribute value");
    return;
  }

  function setColors(colorObject, animate) {
    if (typeof gsap !== "undefined" && animate) {
      gsap.to(htmlElement, {
        ...colorObject,
        duration: colorModeDuration,
        ease: colorModeEase
      });
    } else {
      Object.keys(colorObject).forEach(function (key) {
        htmlElement.style.setProperty(key, colorObject[key]);
      });
    }
  }

  function goDark(dark, animate) {
    if (dark) {

CSS variables:

:root {
    --swatch--light: white;
    --swatch--transparent: rgba(255, 255, 255, 0);
    --swatch--brand: #8a2d59;
    --swatch--color: #1f1e3e;
    --swatch--dark: #201c1c;

    --color--background: var(--swatch--light);
    --color--text: var(--swatch--dark);
    --color--button-background: var(--swatch--brand);
    --color--button-text: var(--swatch--light);
    --color--toggle-bg: var(--swatch--light);
    --color--nav-menu-link: var(--swatch--light);
    --color--toggle-offset: 0rem;
    --color--background-50: rgba(255, 255, 255, .5);

    --dark--background: var(--swatch--dark);
    --dark--text: var(--swatch--light);
    --dark--button-background: var(--swatch--brand);
    --dark--button-text: var(--swatch--light);
    --dark--toggle-bg: var(--swatch--brand);
    --dark--nav-menu-link: var(--swatch--light);
    --dark--toggle-offset: 2 rem;
    --dark--background-50: rgba(53, 50, 51, .5);
}

Answer №1

The main issue stemmed from the fact that when transforming the webflow site into a theme with the help of udesly, the css import was inadvertently placed below the script tag containing the javascript.

By manually adjusting the script to load after the css-variables, the problem was swiftly resolved.

Check out the working example here

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 jQuery, Ajax, and PHP to Transfer Both FormData and String Data

I want to pass a FormData value and some String values to a PHP page. Below is my JavaScript code: $.ajax({ url: 'upload-pic.php', type: 'post', data: { type : type, ...

The expression suddenly stopped: nextEvent was not expected to happen

It appears that the issue I am facing is not related to interpolation. Despite removing any instances of interpolation in my code, I am still encountering the same error. The error occurs when I click on an ng-click directive that points to a page referen ...

Tips for choosing the parent's parent and applying a width of 100%

I am currently facing some challenges while creating a simple navigation bar from scratch. I am struggling with setting specific widths, especially wanting .navbarDropBtn to align its width with .navbarMain. However, it seems to only match the width of the ...

Header and footer remain unaligned

Bookstore.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> ul { list-style-type: none; padding: 20px; overflow: hidden; background-color: black; width:1230px; p ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

Who should take the lead in processing data to render the view: the parent or child component in ReactJs?

As I embark on my journey to learn ReactJS, a burning question arises in my mind: When the parent component fetches data from a server using a GET request and receives a JSON object, what is the best approach for passing these attributes to a child compone ...

The child element fails to update when the props are altered

Below is the main component structure : state = { books: undefined } componentDidMount() { BooksAPI.getAll().then(books => { this.setState({books},this.filterBooks); }); } filterBooks() { this.currentlyReading = this ...

How effective is Dojo CodeGlass?

When working with Dojo, I have encountered a situation where the sample codes should be functional based on the references provided. However, after attempting to run the code, I am faced with a blank page. It seems as though I may have overlooked somethi ...

Cannot adjust dimensions of Chart.js

Struggling to resize chart.js on an HTML page. Have attempted various methods like adjusting the canvas parameters, defining section and div tags, explicitly setting height and width in <style>, as well as using {responsive: true, maintainAspectRatio ...

What is the optimal approach for managing multiple languages using React Router version 5?

I am exploring the possibility of incorporating multiple languages into my website using React and React Router v5. Can you provide guidance on the most effective approach to achieve this? Below is a snippet of the current routing code I am working with: ...

Encountering a problem when trying to submit data on a form in Prisma Nextjs due to an

As I construct an editing feature for objects within my postgres database, I am encountering an issue related to form submission. Specifically, when attempting to update fields defined in the schema, I am receiving an error message: client_fetch_error unde ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

Get rid of the seconds in the output of the toLocaleTimeString

The method Date.prototype.toLocaleTimeString() provides a language-sensitive representation of the time part of a date in modern browsers. Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows ...

"Centered in the middle of the screen, an animated

Encountering an issue with this code on Chrome. Clicking on the checkbox causes the text/checkbox to shift in position/padding/margin unexpectedly.. :( View the code on JSFiddle HTML <input id="inp" type="checkbox" /> <div id="cb" class="inp_ch ...

Begin Theme Eliminate Service Post Type

Looking to eliminate the services post type from the Start Genesis child theme. Upon checking, I noted that the Start theme includes a services post type. There is a page with the URL -- -- however, attempting to view the page at this address results in a ...

Updating a div using jQuery within a loop and showcasing all the values

I have implemented a foreach loop for the items in my cart. When I click on either the plus or remove buttons, the $value is updated correctly. However, I am seeing double the value in each row. Here is my script: <script type="text/javascript> ...

Discover the optimal approach for merging two jQuery functions effortlessly

The initial function (which can be accessed at ) is as follows: $('#confirm').confirm( { msg: 'Before deleting a gallery and all associated images, are you sure?<br>', buttons: { separator: ' - ' } } ); ...

Double Ajax calls being made in Laravel application

I am working on a Laravel application for managing tasks. The application has a form with four fields: one for the CSRF token, two hidden fields for IDs, and an input field to capture the task title. For submitting the form, I have implemented AJAX. Howev ...

Challenges arising from incorporating a nested for loop with table output in JavaScript

var data = { "categories":[ "Early Years (RA)", "Primary schools (RA)", "Secondary schools (RA)", "Special schls and alter prov (RA)", "Post-16 provision (RA)", "Other edu and community budget (RA)", "TOTAL EDUC ...