Reputation:
I am very new to HTML design, and am trying to make a button that when click the first time, changes the text to 'Look, I did something!!!', and that works fine. Then, on the next press, I want to change it back to the original. I was able to successfully do that, but once it was done, it wasn't able to be done again. This was that design.
document.getElementById("button").onclick = function(){
document.getElementById("button_text").innerHTML = "Look I did something!!!";
document.getElementById("button").innerHTML = "Go Back";
document.getElementById("button").onclick = function(){
document.getElementById("button_text").innerHTML = "Click Me. I'm a button!!!";
document.getElementById("button").innerHTML = "Click Me";
}
}
Can somebody please help me with this, as I really have no idea how to make this work.
Upvotes: 0
Views: 218
Reputation: 277
A simple way to toggle a button's text:
let active = false;
document.getElementById("button").onclick = () => {
// "Toggle" the active variable, if false it becomes true, and vice-versa
active = !active;
// Render different button text based on whether active is true or false
if(active){
document.getElementById("button").innerHTML = 'Look I did something!!!';
}
else {
document.getElementById("button").innerHTML = 'Click me';
}
}
<button id="button">Click me</button>
This is obviously very customizable depending on your needs.
Upvotes: 1