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.
Below code i tried
import $ from "jquery";
$(document).ready(function(){
$("#root").click(function(){
if (rootApp.innerHTML === ''){
rootApp.innerHTML = '';
} else {
rootApp.innerHTML = '';
}
})
})
const rootApp = document.getElementById("root");
rootApp.innerHTML = '';
it is working fine but do we have any other way to do it better way.
Prasad RaveendranPosted Sep 3, 2023, 6:46 PM
You can improve the code by simplifying the logic and avoiding direct manipulation of the
innerHTML. Here's a cleaner version of your code using event delegation and a more concise approach:And in your HTML, you can initially set the button text:
In this version:
We use event delegation by attaching the click event handler to the
#rootelement. This way, you don't need to worry about dynamically created elements within#root.We give the button an
id(in this case,toggleButton) for easy selection and manipulation.Inside the click event handler, we use the
text()method to toggle the button text between "ON" and "OFF" without modifying the innerHTML directly.By making these changes, the code is more maintainable and easier to understand.
Tahir AnsariPosted Sep 3, 2023, 7:55 AM
Lokesh VarmanPosted Sep 3, 2023, 3:41 AM
Your code works fine for toggling the button between ON and OFF states. However, you can simplify it a bit by using a data attribute to keep track of the current state. Here's an updated version of your code: