Need help with JavaScript?

I am a beginner and I am just getting to the point where I know the basics of JavaScript, but there is one thing that I need to know. Say I was making a button that would change the text in an HTML paragraph. I know how to change it once or many times with one click, but how would I make it so that the button would change the text to something different every time I click it? Would I be able to create an array and use a for loop to return a different length each time? Is there some way to break the script after the first click? I would greatly appreciate any help. Thanks in advance.

Update:

In response to abc’s answer, I’m not sure how the random() method would help me accomplish this task?

✅ Answers

🥇 Favorite Answer

  • Use Math.random() to generate a random number.

    https://developer.mozilla.org/en-US/docs/JavaScrip…

    “Returns a floating-point, pseudo-random number in the range [, ) that is, from (inclusive) up to but not including (exclusive), which you can then scale to your desired range.”

    Combined with Math.floor and the length of your array, you can generate a random integer between and including and the last index number of your array. So something like:

    var randomIndex = Math.floor(Math.random() * text.length)

    Then you can create an if statement. If your <p> tag is empty then assign it the the text from your array element at randomIndex.

    If you want the text to be different each time then add an else to your if statement. Make a loop that runs while the innerHTML property of your <p> tag is equal to the text array element at randomIndex. In the body of the loop, generate a new random number. The loop will automatically stop when the innerHTML of your <p> tag and the text in the your array at randomIndex don’t match.

    See also  I did ALL THE THINGS RIGHT!! But my Minecraft server won't work! Why is this?

    Then the program can assign the text from the array at randomIndex to the innerHTML property of your paragraph.

    Here’s an example.

    http://pastebin.com/hTRcXFK

    – Dominic

  • how would I make it so that the button would change the text to something different every time I click it?

    – https://developer.mozilla.org/en-US/docs/JavaScrip…

    may help

    random number can be used to retrieve a string at random index position of array of strings

    Would I be able to create an array and use a for loop to return a different length each time?

    – yes

    Is there some way to break the script after the first click?

    – don’t know

  • you’re taking a type and you will desire to be taught Javascript? Then do no longer ask for an entire answer. Your instructor will probable be able to tell beginner code from expert code. All you will desire to do is be taught the thank you to write down a loop and use an “if” assertion with a modulus operator.

  • Leave a Comment