How do I make it so if my button is clicked a second time the text goes back to what it originally was? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do I make it so if my button is clicked a second time the text goes back to what it originally was?

I want a button that can change text on the screen. https://code.sololearn.com/WW3QwZhnn4MZ/?ref=app

18th Mar 2018, 3:31 AM
Babydoll Scripts
Babydoll Scripts - avatar
3 Answers
+ 3
If you only have 2 values then you can just swap them each time the button is clicked. let a = ""; let b = "Text changed successfully!"; function myFunc(){ let box = document.getElementById("box"); a = box.innerHTML; box.innerHTML = b; b = a; }
18th Mar 2018, 4:35 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Chaotic Dog, what you said works but I'm confused about how it works. Can you try to explain what's happening in the code?
18th Mar 2018, 4:46 AM
Babydoll Scripts
Babydoll Scripts - avatar
+ 2
a = box.innerHTML; This will get the current value and store it in a. The first time the button is clicked it will get the text coded in the html p tag "Text here" box.innerHTML = b; This gets the text currently stored in b and sets it as the box innerHTML. The first time the button is clicked it will get the text "Text changed successfully". b = a; This stores whatever is currently stored in a also in b. The first time the button is clicked b will also be "Text here". This allows a to be changed the next time the button is clicked in the first line of code above to "Text changed successfully" so that at least 1 copy of each value is always stored somewhere in your code, either in one or both of the JS variables or within the HTML's p tag (box).
18th Mar 2018, 8:42 AM
ChaoticDawg
ChaoticDawg - avatar