2021年4月9日星期五

Uncaught TypeError: can't access property "onclick", modal box on specific pages

What I'm trying is to display a modal box on specific product categories. Everything working, but I get this error from MDN: "Uncaught TypeError: can't access property "onclick", btn is null"

Here is my code:

//Modal Product Category = Ring    add_action('woocommerce_after_add_to_cart_form', 'monoscopic_modal', 15);  function monoscopic_modal() {      global $product;      ?>          <?php if( has_term( 'ring', 'product_cat', $product->id ) ) : ?>               <!-- Trigger/Open The Modal -->              <button id="myBtn">Open Modal</button>                <!-- The Modal -->              <div id="myModal" class="modal">                <!-- Modal content -->              <div class="modal-content">                  <span class="close">&times;</span>                  <p>Some text in the Modal..</p>              </div>                </div>           <?php endif; ?>                <script>                  // Get the modal                  var modal = document.getElementById("myModal");                    // Get the button that opens the modal                  var btn = document.getElementById("myBtn");                    // Get the <span> element that closes the modal                  var span = document.getElementsByClassName("close")[0];                    // When the user clicks the button, open the modal                   btn.onclick = function() {                  modal.style.display = "block";                  }                    // When the user clicks on <span> (x), close the modal                  span.onclick = function() {                  modal.style.display = "none";                  }                    // When the user clicks anywhere outside of the modal, close it                  window.onclick = function(event) {                  if (event.target == modal) {                      modal.style.display = "none";                  }                  }              </script>        <?php  }  

What's going wrong? Any help?

Thanks

https://stackoverflow.com/questions/67030190/uncaught-typeerror-cant-access-property-onclick-modal-box-on-specific-pages April 10, 2021 at 10:08AM

没有评论:

发表评论