Reputation: 1
a piece of code that shows a piece of text after the button is clicked, how would I use that code for multiple buttons with each button giving a unique piece of text. how to position the outputted text. And how to make the text replace the one from the previous text from another button. Thank you so much!
<button onclick="typeWriter()">Click me</button>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
Upvotes: 0
Views: 174
Reputation: 6077
Pass some data on button click handler to identify which text to show. Below is a working example.
var lines = ["Demo text line one", "This is line two", "And this is 3rd and final line"];
var speed = 50;
var elim = document.getElementById("demo");
function showText(btnId) {
var text = lines[btnId - 1];
var printer = setInterval(printChar, speed);
var i = 0;
function printChar() {
if (i > text.length) {
clearInterval(printer);
} else {
elim.innerHTML = text.slice(0, i);
i++;
}
}
}
<p id="demo"></p>
<button onclick="showText(1)">One</button>
<button onclick="showText(2)">Two</button>
<button onclick="showText(3)">Three</button>
Upvotes: 2
Reputation: 4519
You have 3 different questions, but I believe what you are looking for is this:
<!-- Here you can pass a parameter with the desired text -->
<button onclick="writeText('Text 01')">Click me</button>
<button onclick="writeText('Text 02')">Or click me</button>
<p id="demo"></p>
<script>
var i = 0;
var txt = '';
var speed = 50;
// This new helper function will be used to clear time and previous text
function writeText(newTxt) {
i = 0;
txt = newTxt;
document.getElementById("demo").innerHTML = "";
typeWriter();
}
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
Here is the working example: https://codepen.io/brunomont/pen/YzKREdr?editors=1000
Upvotes: 1