Change Div Width% using Sugarcube2 variables and Javascript

Alright, my unfamiliarity with JavaScript syntax is killing me here. If I spend any longer ramming my head into this brick wall I’ll go mad, so I came here to ask somebody who actually knows what they’re doing.

Okay, so I’m working with divs, something similar to this;

#GenericDiv {
  	position: absolute; 
  	background: red;
  	right: 0%;
  	top: 0%;
	width: 100%;
  	height: 100%;
  	z-index: 1;
}

And I want to change this div’s starting width % using a JavaScript code somewhat similar to this (not functional code)

setup.changewidth = function() {
	var a = document.getElementById('GenericDiv');
	var percentage = ((SugarCubeVariable1 / SugarCubeVariable2) * 100) + '%';
		a.style.width = percentage;
		a.style.transition = "all 1s";
};

But I have no idea how to input the SugarCube variables so that the JavaScript will play nicely, It just keeps throwing errors at me or doing nothing at all. All I need is to convert two variables into a percentage and set the width to that same percentage.

The SugarCube documentation lists several methods for accessing both story and temporary variables within JavaScript.

The basic way to access story variables is the State.variables API—the variables() function provides equivalent access if you’d prefer that. For example, the following access the story variables $var1 and $var2:

var percentage = ((State.variables.var1 / State.variables.var2) * 100) + '%';

Though, you may take a local reference to State.variables to shorten your code when needing to reference it multiple times. For example:

var sv = State.variables;
var percentage = ((sv.var1 / sv.var2) * 100) + '%';

Accessing temporary variables would be similar, though the APIs differ: State.temporary and temporary()

1 Like

In addition to what TheMadExile said, you might want to take a look at my health bar sample code, since it does something very similar to what you appear to want. Instead of using SugarCube variables, you simply pass the data as parameters to a Health() function, and it takes care of displaying the healthbar appropriately. (Click “Jump to Start” in the UI bar to see other sample code there.)

Hope that helps! :slight_smile:

1 Like

Whoops, it seems like I made a embarrassing mistake. I’d looked at the SugarCube documentation earlier and tried everything I could to get it working but In half of my attempts I had incorrect JavaScript syntax and the other half had a misspelled variable that I overlooked.

Everything works just fine now, thanks for the help. The final working code is below, for anybody interested. It’s nearly identical to the code I started with, only with less dumb.

setup.changewidth = function() {
	var a = document.getElementById('GenericDiv');
	var percentage = ((State.variables.Var1 / State.variables.Var2) * 100) + '%';
		a.style.width = percentage;
		a.style.transition = "all 1s";
};