Home > Enterprise >  Using a button to display different texts using javascript
Using a button to display different texts using javascript

Time:10-07

I want to use a button to display a text with the styles and to revert to the original text when I click the button again. I have done the first part which is to display the text but I cant revert back to the original text. This is what I have so far:

function myFunction() {
  document.getElementById("second").innerHTML = "Hello Javascript";
  document.getElementById("second").style.fontSize = "25px";
  document.getElementById("second").style.color = "red";
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>

CodePudding user response:

Declaring a a variable let count = 1; outside the function which will help me to check the state i am in currently in.so first i assigned the value of 1 to it.

in my function i am saying is count is equal to 1 change it to Hello Javascript with other properties and change count to zero.so when you click the next time count is now zero and the first if gets rejected instead it goes to the second if else condition and makes it this is me and changes count to 1 this time.

basically changing the text with count as a statemanagement.

let count = 1;

function myFunction() {

  if (count == 1) {
    document.getElementById("second").innerHTML = "Hello Javascript";
    document.getElementById("second").style.fontSize = "25px";
    document.getElementById("second").style.color = "red";
    count = 0;
  } else if (count == 0) {
    document.getElementById("second").innerHTML = "This is me";
    document.getElementById("second").style.fontSize = "16px";
    document.getElementById("second").style.color = "black";
    count = 1;
  }

}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>

CodePudding user response:

perhaps using sequence style

  • Related