Show and hide text by clicking a button | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Show and hide text by clicking a button

hi. i want to show a line/group of text by clicking a button and at the same time hide it after im done reading the text. ... the text should originally be hidden when the user arrives at the page. thank you and god bless

21st Jun 2018, 1:59 PM
De Wei
De Wei - avatar
5 Answers
0
It's simple, make a class in CSS .hidden and set in on your HTML elements you would like to hide at the start. In CSS: .hidden { display: none; } In HTML <p class="hidden">My text </p> Then use javascript and create a function and attach event listener on button to toggle this class on and off whenever you click on the button.
21st Jun 2018, 2:14 PM
damyco
damyco - avatar
0
hi thanks for the reply. hmmm i did what you ask me but im having a problem. the button needs to be clicked twice or 3 times before the text show but after that it runs smooth but when i refresh the page i wll have to click the button twice or 3 time again. any advice sir?
21st Jun 2018, 2:19 PM
De Wei
De Wei - avatar
0
Try loading JS after the DOM is generated.
21st Jun 2018, 2:21 PM
damyco
damyco - avatar
0
sir what do you mean by that? sorry im just new to js so im having problems😅. thanks for understanding
21st Jun 2018, 2:24 PM
De Wei
De Wei - avatar
0
Apparently SL engine is silly and loads JS first and then DOM. So if you are trying to grab elements with JS it's throwing errors. Try wrapping your whole code in this function (there are many ways of doing this) document.addEventListener("DOMContentLoaded", () => { //your code here }; this will wait for event which is DOM content loaded and as soon as it is, it will start executing your code.
21st Jun 2018, 3:21 PM
damyco
damyco - avatar