Blog

Toggle Button JavaScript Function

 



And the corresponding HTML for the button:

<button onclick="toggleVisibility('target-element-id')">Toggle</button>
<div id="target-element-id">This element will be toggled</div>



Here is a simple JavaScript function to toggle an HTML element's display property on a button click:

function toggleVisibility(elementId) {
  const element = document.getElementById(elementId);
  if (element.style.display === "none") {
    element.style.display = "block";
  } else {
    element.style.display = "none";
  }
}