#How can I make buttons that show text when clicked

17 messages · Page 1 of 1 (latest)

green sedge
#

So I have figured out how to make a button that can display text but how am I supposed to make it so when I click on a different button it needs to display a different paragraph of text. Note Im really new to coding, programming just started making a passion project along side a html and css youtube guide so im self taught and need help with this functionality that I am trying to implement.

torpid crescent
green sedge
#

html
<button onclick="displayText()">Click Me!</button>

<div id="textField" style="display: none;">
This is the text that appears when you click the button.
</div>

#

JS
function displayText() {
var text = document.getElementById("textField");
text.style.display = "block";
}

#

this is what i managed to find but when i tested it with multiple buttons

#

it just stayed with the same text from the 1st button

#

and if i refresh and click a different one it still displays the first button

#

I am pretty sure im supposed to write more in the js part about conditions but im not sure how to go about it since I have done just the very basics and that was a few months ago

frank rock
#

do you understand what the code you currently have is doing? once you understand it, you should be able to think through how to do the same thing for multiple buttons

#

let me explain

#

onclick="displayText()" on the button means it will run the displayText function when the button is clicked

#

inside your displayText function

#

getElementById is getting the <div> with the id textField, its the div that has id="textField"

#

then the next line is setting the CSS display:block on that div

#

which was display:none before (look at the div after the style=)

#

display none means it wont show it, versus display block which will show it

#

does that all make sense?