i’m pretty new to html/javascript, and i’m trying to develop a visual novel online, and i want to create a "click to advance" feature, so everytime you click a new piece of text appears, like for example higurashi and tsukihime. I can’t seem to create the feature because whenever i do an "onclick" function, it spits out all the text at once.
document.querySelector("html").addEventListener("mousedown", function One() {
const para = document.createElement("span");
const node = document.createTextNode("Z.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
return;
});
document.querySelector("html").addEventListener("mousedown",function Two() {
const para = document.createElement("span");
const node = document.createTextNode("A.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
});
<div id="div1"></div>
I expected it to work in the way that when you click, it creates a set of text, and then when you click again, it makes another set of text. unfortunately, everytime you click, it just spits out all of the content. should i use an await/promise function? Do I need a handler? How do I set that up? How do you clear the text and make new text after you’re done with a scene?
3
Answers
For accessibility reasons, you should provide your entire content in the HTML itself instead of dynamically creating it with JS.
Then you hide all those sections with the exception of the first by default. After that, you can add a class to the next class with JS to make them visible again:
First of all, while it’s not inherently wrong to use text nodes, in this scenario, they are unnecessarily complicating your code. Creating and appending text nodes for each piece of text makes the code way harder to manage.
I would highly recommend starting with tutorials on html/js (W3Schools or any other) tutorial before working on a large project like a visual novel.
To solve your particular problem, I propose this solution:
We store the text values in an array, but you can use any other method to pass the values if you wish. The eventListener is then attached to the whole document, so you can click any part of the page to advance the text.
You don’t want to use await/promise here, as asynchronous programming is used to keep your program responsive even if you have a long-running task running in the background.
In fact, you use a "handler" the moment you add an event listener to your program. In this case, the event handler is the changeText function.
You could first load your content, and then build the HTML from it.
The HTML your construct can be pre-hidden. As your request more content, you can remove the
.hidden
class.The example below uses Faker (to generate the content) and Tailwind (for CSS presentation).
Note: The Faker API supports
{ min, max }
arguments, but I could not get them to work, so I used arandInt
function.