+ 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
3 Respostas
+ 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;
}
+ 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?
+ 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).