i want to change a paragraph text with HTML and JAVASCRIPT by clicking a button. I just found a lot of codes where you can click the button just one time. I need a button which i can click multiple times to change it to the next paragraph. I need to put in more values
I need help to write the code
2
Answers
From what I understood, you want a button that switches between different paragraphs?
If I understood well, the best way to approach it would be to have an array with all the different paragraphs, and make the button rotate between those. This can be done in HTML and JS.
Since you’ve not shared any code, I’m going to guess the paragraph and button look like this
To change the paragraph, first you should make an array that contains all the paragraphs
This makes a "list" with all the paragraphs you’re going to switch between.
Then you grab the paragraph element (We will be changing the HTML of this element)
We’ll also make an index variable, that stores in what paragraph we’re in, so we can switch to the next one
With all this prep work done, you can now work on the function. First, we need to increment the index value, but if it’s over the length of the array, go back to zero.
After that, just replace the content of the
<p>
element using element.innerHTML and the index as the index of the array.With all this together, your code should look like this:
Here’s a JSFiddle to try it out:
https://jsfiddle.net/9h8Lven5/18/