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?
>Solution :
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:
<!DOCTYPE html>
<html>
<body>
<div id="text">Click anywhere to advance the text...</div>
<script>
// Array of texts
var texts = [
"This is the first text.",
"This is the second text.",
"This is the third text.",
"This is the final text."
];
var index = 0;
var textElement = document.getElementById('text');
// Function to change text on click
function changeText() {
textElement.textContent = texts[index];
if (index < texts.length - 1) {
index++; // Increment index until the second last text
}
}
// Event listener to detect clicks
document.addEventListener('click', changeText);
// Initial text display
changeText();
</script>
</body>
</html>
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.