Sugarcube 2 - Insert div

I want to insert a div after a passage:

The JS is in the Story JS and the CSS in the Story Stylesheet.

$("<div id='case_1_image'></div>").insertAfter($("#passage-cs1-p1"));

#passage-cs1-p1{
  background-image: url('images/case_1.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

#case_1_image {
  position: fixed;
  top: 0;
  right: 0;
  width: 300px;
  background-color: red;
  height: 100%;
}

The div #case_1_image is not showing and also not in the page source.

What am I doing wrong?

BTW the div #passage-cs1-p1shows the background image fine.

Why not just add <div id='case_1_image'></div> in the passage directly? Like at the bottom of the coded passage?

:: CS1-P1
Whatever code + text you have in the passage

<div id='case_1_image'></div>
1 Like

Ah, new to Twine, but that makes sense!

Cheers

Peter

1 Like

The reason your code didn’t work, is because there is no #passage-cs1-p1 when your javascript runs.

The contents of the Story Javascript runs as soon as your game is loaded, before any of the passages exist. Even if it ran slightly later, there would still not be a #passage-cs1-p1 unless that’s the very first passage of your game, because passages don’t exist as elements in that way unless they are the current passage.

If you need to run Javascript when some particular passage loads, you can either put it in the passage directly inside a <<script>> macro, or (better practice) use an event listener to listen for the passage load events and do something there.

1 Like

There is a “PassageFooter” you can add (a specially named passage) that will get added to the bottom of every page. You might want to do it that way.

1 Like