Click here to Skip to main content
15,851,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
We provided some simple JavaScript template code. Your goal is to modify the application so that you can properly toggle the button to switch between an ON state and an OFF state. When the button is on and it is clicked, it turns off and the text within it changes from ON to OFF and vice versa. You are free to add classes and styles, but make sure you leave the element IDs as they are.

What I have tried:

I tried the below code:
JQuery
import $ from "jquery";

$(document).ready(function(){
  $("#root").click(function(){
    if (rootApp.innerHTML === '<button>ON</button>'){
      rootApp.innerHTML = '<button>OFF</button>';
    } else {
      rootApp.innerHTML = '<button>ON</button>';
    }
  })
})

const rootApp = document.getElementById("root");
rootApp.innerHTML = '<button>ON</button>';


It is working fine, but do we have any other better way to do it?
Posted
Updated 13-Sep-23 5:29am
v3
Comments
Dave Kreskowiak 2-Sep-23 18:59pm    
There's a ton of other ways to do this. Your code adds and removes the button, but you can just leave the button in place and change its attributes to change the button.

1 solution

You were almost there -


JQuery
import $ from "jquery";

$(document).ready(function(){
  $("#root").click(function(){
    //Get the current text content of the toggle button...
    const buttonText = rootApp.innerHTML;

    //Check if the button is in the ON state...
    if (buttonText === 'ON'){
      //If it is ON, change it to OFF and update the text...
      rootApp.innerHTML = 'OFF';
    } else {
      //If it is OFF, change it to ON and update the text...
      rootApp.innerHTML = 'ON';
    }
  })
})

const rootApp = document.getElementById("root");
rootApp.innerHTML = 'ON';
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900