0

Is it possible to amend the below code so that when you click on a button with the ID #slide-1-next , the javascript code runs? Ideally the code would not run until the button has been clicked. Im not super well versed in JS but I think maybe the last line of code with the event listener can be amended to achieve this?

let text = 'What follows is Lorem ipsum translated to English: But I must explain to you how all this mistaken idea of reprobating pleasure and extolling pain arose.';

function type() {
    let textChar = text.charAt(textLength++);
    let paragraph = document.getElementById("typed");
    let charElement = document.createTextNode(textChar);
    paragraph.appendChild(charElement);
    if(textLength < text.length+1) {
        setTimeout('type()', 50);
    } else {
        text = '';
    }
}
  
document.addEventListener("DOMContentLoaded", function() {
    type();
  });
gjjr
  • 607
  • 5
  • 13
  • Take a look at https://stackoverflow.com/a/1947531/16688813 – Tom Oct 27 '21 at 16:04
  • 3
    Does this answer your question? [Using an HTML button to call a JavaScript function](https://stackoverflow.com/questions/1947263/using-an-html-button-to-call-a-javascript-function) – Tom Oct 27 '21 at 16:04
  • thanks @Tom I tried changing the last line of code to ```document.getElementById("slide-1-next").onclick = doFunction;``` But it didnt work... – gjjr Oct 27 '21 at 16:08
  • 1
    try with `document.getElementById("slide-1-next").onclick = type;`. The function `doFunction` is not defined in your case. – Tom Oct 27 '21 at 16:13
  • yessss! thank you so much. – gjjr Oct 27 '21 at 16:16
  • Would you also know how to add paragraphs of text for 'let text ='? currently the text is all on one line but i need to break it up into paragraphs. Thanks in advance – gjjr Oct 27 '21 at 16:33

1 Answers1

1

To summarize the comments above, adding the following line at the end of your code block will run the type function when the button with ID slide-1-next is clicked:

document.getElementById("slide-1-next").onclick = type;
JonathanDavidArndt
  • 2,518
  • 13
  • 37
  • 49