How to make the background of a passage dependent on a variable

Twine Version: 2.3.15
Story Format: SugarCube 2.34.1

The only way I know to add a background-image for a passage is to do so in the stylesheet, but I can’t find a way to incorporate conditional statements (or something similar) in these. Basically, what I want is for the background of a passage to be different depending on the time of day, or any other variable. I don’t want to create a separate passage just so I can have a different background for it.

So, a way to add a background-image in the passage code itself would allow the background to change depending on an <> statement. Alternatively, doing it in the stylesheet might be more practical. Any solution would be greatly appreciated.

Add all the background images in the stylesheet, each one with a different class. Example:

:: UserStylesheet[stylesheet]
.day {
  background-image: url("...");
}
.night {
  background-image: url("...");
}

Now you can use If or Switch to toggle the class based on a variable:

:: Passage

<<set $time to "day">>\
<<if $time is "day">><<toggleclass "body" "day">><</if>>\
<<if $time is "night">><<toggleclass "body" "night">><</if>>\

Thank you, that works perfectly and answers my question. But is it possible to do this with this stylesheet? I’m not sure how to refer to it in the <> and I’m also not sure if it would work given that the blur effect needs to happen before anything else.

:: Stylesheet
body[data-tags~=“classroom”]:before {
content: ‘’;
z-index: -1;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-image: url(“images/bg/classroom.webp”);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
-webkit-filter: blur(5px);
filter: blur(5px);
}

(and @Yadex )

If you are storing the name of one of the associated CSS classes (eg. “day” or “night”) within the $time variable then there is no need for the set of <<if>> macro calls.

Instead you would use the <<removeclass>> macro to first remove all of the associated CSS classes from the target element, and then add back the current value of the variable.

<<removeclass "body" "day night">>
<<addclass "body" $time>>

And because you potentially want this for each Passage Transition you may want to add the above coded to a either a PassageReady or PassageDone special Passage.

1 Like