Home > database >  How to Toggle (Hide/Show) an Element in JavaScript
How to Toggle (Hide/Show) an Element in JavaScript

Time:12-08

I have an invoice webapp and trying to add a button to Toggle (Hide/Show) invoice stamp before printing/saving pdf but I can't make it work.

Stamp part : source from ".json" template file

<?php
    $etat_footer .= "<div class=\"col-xs-4\">";
    if( trim($signature_stamp) != "" ){
      $etat_footer .= "<p style=\"text-align: center; border-bottom: 0px solid #666;\">
        <img src=\"".($signature_stamp)."\" style=\"max-width:1px; max-height:160px; margin-bottom:-1px;\" />
      </p>";
      ?>
      <?php
      
    }else{
      $etat_footer .= "<p>&nbsp;</p><p style=\"border-bottom: 0px solid #666;\">&nbsp;</p>";
    }
    $etat_footer .= "<p class='text-md-center'>".$signature_txt."</p>
    </div>";
  }else{
    $etat_footer .= "<div class=\"col-xs-4 col-xs-offset-8\">";
    
      $etat_footer .= "<p style=\"text-align: center; border-bottom: 0px solid #666;\">
        <img src=\"".($signature_stamp)."\" style=\"max-width:170px; max-height:160px; margin-bottom:-1px;\" />
      </p>";
    
    $etat_footer .= "<p class='text-md-center'>".$signature_txt."</p>
    </div>";
  }
}
?>

I tried creating a button with the function to hide the element but did not work:

<button onclick="myFunction()">Hide/Show Stamp</button>

Javascript

<script>
function myFunction() {
  var x = document.getElementByClassName("col-xs-4 col-xs-offset-8");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

CodePudding user response:

Two notes:

  • probably you want to use getElementsByClassName, since getElementByClassName by default is not decelerated.
  • in case you use getElementsByClassName, don't forget to select result element

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Working example bellow:

function myFunction() {
  var x = document.getElementsByClassName("col-xs-4 col-xs-offset-8");
  if (x[0].style.display === "none") {
    x[0].style.display = "block";
  } else {
    x[0].style.display = "none";
  }
}
<div >
STAMP
</div>
<button onclick="myFunction()">Hide/Show Stamp</button>

  • Related