I current am working on a project and I want to add the ability to add custom themes. I have a basic structure for a theme. Below is the basic structure of a theme and it’s location
Probably, but I don’t mess with JS too much, so I’m not certain. The only thing I’m certain of is the fact that in it’s current position, it’s undefined.
You seem to doubling up on attempting to append to the head, I would suggest just removing the second one because it it isn’t even inside the request callback function.
Are you getting errors in the console? If you haven’t checked, I suggest you do. You can’t use - in a variable name, if you want to use -, use a string as the property accessor like this: data["background-color"].
link isn’t defined, although it could be because of JavaScript’s shady past. Basically, var is the old variable declarator, the new ones are let and const (nowadays, I would always consider it bad practice to use var). var used to work by putting everything in the global scope (let and const are both local scope and const is immutable for strings, numbers and booleans) so technically it could be defined, however this is jQuery making a get request, so because the callback function won’t be called immediately given a request will take some time, it shouldn’t be defined.
I notice that you were setting CSS variables on a root object, but root was not defined anywhere in the code you posted. You can add a let root to your script to define the root and set it to the root element.
var load = function() {
$.getJSON('static/themes/default/default.json', function(data) {
let theme = data;
console.log(theme)
let root = document.documentElement; //right here
root.style.setProperty('--bgClr', theme.backgroundColor);
root.style.setProperty('--txClr', theme.textColor);
root.style.setProperty('--uiClr', theme.interfaceColor);
root.style.setProperty('--olClr', theme.outlineColor);
root.style.setProperty('--nlClr', theme.navbarItemColor);
root.style.setProperty('--avClr', theme.activeColor);
$('head').append(`<link rel="stylesheet" type="text/css" href="${theme.customCssPath}">`);
});
};
Be sure to call the load() function after the HTML is fully loaded.
What does default.json look like? If it has a key called custom-css-path, then instead of doing theme.customCssPath you should do theme["custom-css-path"]