r/twinegames • u/Jack_Jacob_Jimmy • 1d ago
SugarCube 2 Question: How to set a css variable.
Hello, newbie here, so I'm working on a project and I need to know how to set a css variable that is px. using <<script>> document.documentElement.style.setProperty('--position-y', '4'); <</script>> because of a calc in my story stylesheet, but it does not work when I'm trying to use a $variable, anyone knows how to fix this?
Edit: just to make things more clear, instead of turning my --position-y into 4px I want to add 4px to it.
1
Upvotes
3
u/HiEv 1d ago
First, modifying the existing CSS on the fly can be... painful, due to how CSS works. It's usually far simpler to just modify the individual HTML element(s) on the fly instead.
Second, if you do that, keep in mind that the HTML element you want to modify needs to actually be rendered to the document before you can modify it. The simplest way to make that work is to run any such code within a <<done>> macro.
Third, SugarCube includes jQuery, which makes modifying HTML elements via JavaScript much easier.
So, if you have a particular element you want to target, then you could just do something like this:
using the jQuery .css() method.
Fourth, you could instead use the SugarCube evaluation directive to set an element's "style" attribute, like this:
You can probably use either of the above methods to simply change either the
margin-toporpadding-topto achieve the same thing as increasing--position-y.Fifth, if you only need to modify the position if certain HTML elements precede it, then you may even be able to make a CSS rule which will automatically add the 4px in that particular case.
If none of that helps, post some example passage code and CSS code demonstrating the issue (within Reddit code blocks) and we can take a look at it and possibly work out a better solution for you.
Hope that helps! 🙂
3
u/in-the-widening-gyre 1d ago
I think we might need some more info to help you.
Can you share you stylesheet and the code wherever you're updating things?
What do you want to happen (as far as effect on the page) when you update the variable?
Also what do you mean because of a calculation in your story stylesheet? You can't put JavaScript in a stylesheet so that would be an issue.