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>


:root {
  --origin-color: red;
  --target-color: blue;

  width: 150px;
  height: 150px;

  background-color: var(--origin-color);

  background-color: var(--target-color);

JS (jQuery 3.4.1)

(function( $ ) {
    'use strict';
      $('#toggle-color').on('click', function(event){
        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!)

  • The solution is easy. Even WordPress loads jQuery in the backend, I just had to enqueue my own jQuery.js (here 3.5.1) on the pages in the WP backend where my scripts are used. Now it is working fine. – Tom Jul 24 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.