Load a script exclusively on WooCommerce single product pages

Im using a modal on my WooCommerce single product pages to display additional information for the users, which is only visible at the product detail page. It works also, but the script below is loaded everywhere, so I'm getting the error message:

Uncaught TypeError: Cannot set property 'onclick' of null

When someone is clicking somewhere outside of the product detail page. Is it possible to load the script only at the product detail page?


 <button id="myBtn" class="help-link">Brauchen Sie Hilfe?</button>
    <div id="myModal" class="modal">
      <div class="modal-content">
        <span class="close"><i class="nm-font nm-font-close2"></i></span>
        <h4>Brauchen Sie Hilfe?</h4>
        <p>Sollten Sie Fragen zu Produkten haben, oder Hilfe bei der Konfiguration benötigen, steht unser Kundenservice Ihnen gerne zur Verfügung.</p>
       <p>Erreichbar von Montag bis Freitag<br>10:00 - 18:00 <br>Tel.:040/655 646 91</p>


// 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";



To restrict something in single product pages only use is_product() in an IF statement like:

<?php if ( is_product() ) { ?>
    // your script goes here
<?php } ?>

See Woocommerce conditional tags


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.