-3
let text = ["hello", "world", "where", "list", "tes", "new"];
const btn = document.querySelector(".button");

btn.addEventListener("click", random);
const randomText = Math.floor(Math.random() * text.length);

function random() {
  const pText = document.querySelector(".p-text");
  const textRandom = (pText.innerHTML = `${text[randomText]}`);
}

hy guys, can you help me.? how do I still get random results when I click the button?

  • 1
    Does this answer your question? [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – radulle Jun 22 '20 at 04:04
  • 1
    Move randomText inside of the random function so it's called (and randomized) every time - right now it's set once so each call to `random()` will return the same value. But additionally, please read over [how to ask](https://stackoverflow.com/help/how-to-ask) and edit your question with relevant HTML too (in case your error is there), and what your expected results are. What have you tried to debug your code so far? – WOUNDEDStevenJones Jun 22 '20 at 04:05
  • I'm afraid it's not super clear what you are trying to achieve here. Do you want to change the text on some paragraph element every time someone clicks a button? Not that right now your randomText index is a constant! Change that to a function and you should be go to go. – Marcio Lucca Jun 22 '20 at 04:07
  • Try moving `const randomText = Math.floor(Math.random() * text.length);` to your function `random()`. – bonyem Jun 22 '20 at 04:08

2 Answers2

1

call the randomText inside the random function. because it should run every time you click the button

function random() {
  const randomText = Math.floor(Math.random() * text.length);// here
  const pText = document.querySelector(".p-text");
  const textRandom = (pText.innerHTML = `${text[randomText]}`);
}
Faiz Hameed
  • 488
  • 7
  • 15
1
function random() {
  const pText = document.querySelector(".p-text");
  // move your randomText into function, so that it will have new value when the function is called.
  const randomText = Math.floor(Math.random() * text.length);
  const textRandom = (pText.innerHTML = `${text[randomText]}`);
}
Tan Dat
  • 2,888
  • 1
  • 17
  • 39