javascript toggle button – How To Toggle Between Hiding And Showing an Element?

in javascript toggle button Example, Toggle buttons are basically on/off buttons. We can toggle a button using conditional statements like if-else statement in JavaScript.

javascript toggle button

A button can be switched from on to off state and vice-versa. Create a working toggle switch button from scratch using HTML, CSS.

How to Create a Working Toggle Switch (ON/OFF button) with HTML and CSS?

index.html

<!DOCTYPE html>
<html>
<head><title>How To Toggle Between Hiding And Showing an Element? - www.pakainfo.com</title></head>
<body>
<form>
<input type="button" id="cmnUpdate" value="NO"
       onclick="BtnOnOffData();">
</form>
</body>
<script type="text/javascript">
function BtnOnOffData()
{
  var t = document.getElementById("cmnUpdate");
  if(t.value=="YES"){
      t.value="NO";}
  else if(t.value=="NO"){
      t.value="YES";}
}
</script>
</html>

Example 2:

<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="BtnOnOffData()">Click to Toggle Text</button>

<div id="9898989898">Some Text</div>
</body>
<script type="text/javascript">
function BtnOnOffData()
{
  var t = document.getElementById("9898989898");
  if(t.innerHTML=="Welcome"){
      t.innerHTML="Good Luck";}
  else{
      t.innerHTML="Bad Luck";}
}
</script>
</html>

Example 3: Click to Toggle Class

<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="BtnOnOffData()">Click to Toggle Class</button>

<div id="9898989898">Click Here</div>
</body>
<style type="text/css">
.para-new {
  width: 50%;
  padding: 33px;
  background-color: green;
  color: white;
  font-size: 33px;
}
</style>
<script type="text/javascript">
function BtnOnOffData()
{
  var t = document.getElementById("9898989898");
  t.classList.toggle("para-new");
}
</script>
</html>

Don’t Miss : Bootstrap Toggle Switch Example

I hope you get an idea about javascript toggle button.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this Article are always welcome.
If you enjoyed and liked this post, don’t forget to share.