Getting and setting CSS variables with JQuery in WordPress backend fails


On a WordPress settings page of a plugin I develop, I have to implement a visual element that I want to change by JavaScript. I’ve got my solution working as it should and tested it on code-pen and JSFiddle. But when loading the equivilant code including the script, it will not work.

Here is the schema I’m using: HTML

<div id="origin" class="box"></div> <div id="target" class="box"></div> <button id="toggle-color">Toggle Color</button> 

CSS

:root {   --origin-color: red;   --target-color: blue; }  .box{   width: 150px;   height: 150px; }  #origin{   background-color: var(--origin-color); }  #target{   background-color: var(--target-color); } 

JS (jQuery 3.4.1)

(function( $   ) {     'use strict';     $  (document).ready(function(){               $  ('#toggle-color').on('click', function(event){         event.preventDefault();         var root = $  (":root");         var origin_color = '--origin-color';         var target_color = '--target-color';         var origin_value = root.css(origin_color);         var target_value = root.css(target_color);         root.css(origin_color, target_value);           root.css(target_color, origin_value);         return false;       });   });     })( jQuery ); 

The Problem I have is, that while it is working in test environments in the WordPress backend, the lines where I fetch the colors with

var origin_value = root.css(origin_color); var target_value = root.css(target_color); 

returns ‘undefined’, so the next line where I switch the colors fails.

See my example here: https://jsfiddle.net/tomybyte/hvbc3zu1/6/

I don’t understand why it is working in JSFiddle and code-pen but not when loading in WordPress (yes the code is loaded, I checked that!)