+ 2

Onclick event only works once?

I'm working on a page that uses a clickable div that works as a button. I used the onclick event to make a function that would choose 1 from a variety of random quotes and show it on screen. Unfortunately when the user clicks on the event a quotes does show up, but it only works once. If the user tries to click the div again it doesn't work. What can I do so the clickable event can be triggered more than once and keep choosing one of the variety of quotes that it has with each click. This is the fraction of code I'm having trouble with: <div id = "llamaText" onClick = 'selectQuote'> Click here </div> <script> let quote = ["Always move forward", "Keep fighting", "Never give up"] let randomNum = quote[Math.floor(Math.random()*quote.length)]; function selectQuote() { document.getElementById("llamaText").innerHTML = randomNum; } </script> Thank you to anyone that takes the time to help!

11th Aug 2019, 9:07 PM
HeyItsJay
HeyItsJay - avatar
3 Answers
+ 6
Altough your question has been well answered by Airree and Calvin, please allow me to provide supplements based on my review. Here I am providing two corrections for you. Example 1 : 1.1 The declaration are moved into the function. 1.2 button is used to be more intuitive for user. 1.3 displaying text is separated from the button which triggers the click event. https://code.sololearn.com/WJ9ktupsV3OV/?ref=app Example 2 : 2.1 declaring data in global scope 2.2.a. randomNum based on its name sbould be a number. 2.2.b. It is a function in the global scope. (I assume you know arrow function) 2.3 Calling the function randomNum on every run of selectQuote https://code.sololearn.com/Wy1A40UG1R76/?ref=app Read about scopes : https://www.sololearn.com/post/45261/?ref=app
12th Aug 2019, 10:39 AM
Gordon
Gordon - avatar
+ 4
Just move setting of randomNum statement into function selectQuote, before update llamText.
11th Aug 2019, 10:13 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 2
The problem is that you generate a random number at the start of the script, and use that choice instead. I wrote a shortened code that works fine: <!-- onclick doesn't use camelCase --> <div onclick = "this.innerHTML = ['Always move forward', 'Keep fighting', 'Never give up'][Math.floor(Math.random() * 3)]"> </div>
11th Aug 2019, 9:17 PM
Airree
Airree - avatar