0 votes
by (720 points)

I'm making a RPG fight system. It's going well but there's something I can't figure out. 

I have the text description of the battle appearing in a div id #readout. The text of each turn is appended on the end of it so it contains a full text description of the battle so far. This div will be short but scrollable, and I always want the passage to load with it scrolled to the bottom, so the most recent turn's description is always visible. I found some jquery that was for just this purpose:

<<script>>$("#readout").scrollTop($("#readout")[0].scrollHeight);<</script>>

However, it generates this error:

bad evaluation: Cannot read property 'scrollHeight' of undefined

Undefined? No sir you are mistaken, I think to myself. So I did a test with some more jquery to see what's what.

$("div").addClass("CLASS CLASSY CLASS CLASS");

And I found that this works, but only to divs outside of #passages. So my assumption is that this has something to do with how the passage contents are built and that the <<script>> is run somehow before the rest of the passage's contents exist, even though it's at the bottom of the passage, hence #readout is undefined when the script is run.

Anyway, how do I get my #readout to auto-scroll to the bottom on passage load? 

 

 

1 Answer

+1 vote
by (65.8k points)
selected by
 
Best answer

You're attempting to target an element which has not yet been added to the DOM, because the passage is still being rendered.

You'll want to call your code after the passage has been rendered to the page.  There are several mechanisms in place to allow you to do this.

SEE: http://www.motoslave.net/sugarcube/2/docs/#navigation-events-tasks

by (720 points)
$(document).on(':passagedisplay', function (ev) {
    $("#readout").scrollTop($("#readout")[0].scrollHeight);
});

Thank you, :passagedisplay did the trick.

...