Question is :
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 ID’s as they are.
import $ from "jquery" const rootApp = document.getElementById("root"); rootApp.innerHTML = '<button>ON</button>';
so what i’ve tried
import $ from "jquery" function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } const rootApp = document.getElementById("root"); rootApp.innerHTML = '<input type = "button" value = "ON" id = "button" onclick = "toggle();"/>'
I am new to JavaScript that’s why i am here asking for help.
Advertisement
Answer
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>Javascript Button Toggle</title> </head> <body> <h1>Javascript Button Toggle</h1> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault">Toggle Button</label> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"></script> <script> const btn = document.querySelector('.form-check-input'); const label = document.querySelector('.form-check-label'); btn.addEventListener('change', function(){ this.checked ? label.innerHTML = 'Button Turned On' : label.innerHTML = 'Button Turned Off'; }); </script> </body> </html>