Home > Enterprise >  onclick Modal box in single product page
onclick Modal box in single product page

Time:11-09

I want to create a onclick modal in single product page. I have put together the following:

FILES
js/modal-jquery.js and modal-box.html are uploaded in child theme's directory. css is in child theme's css.

I enqueued the jquery in functions.php

// Enqueue MODAL Jquery JS 
function my_enqueue_stuff() {
    if(is_singular( 'product' ))
    {
        wp_enqueue_script( 'modal-jquery-js', get_stylesheet_directory_uri() . '/js/modal-jquery.js');
// wp_enqueue_script( 'modal-box', get_stylesheet_directory_uri() . 'modal-box.html');
    }
    }
    add_action( 'wp_enqueue_scripts', 'my_enqueue_stuff' );

LINK in functions.php

// POPUP LINK
    add_action( 'woocommerce_before_add_to_cart_form', 'popup-modal', 3 );
    function popup-modal() { 
        // $file = file directory to modal-box.html
        echo '<a  href="#" data-modal-id="popup"> Click me </a>';
    }

modal-box.html

<div id="popup" class="modal-box">  
  <header>
    <a href="#" class="js-modal-close close">×</a>
    <h3>Modal Title</h3>
  </header>
  <div class="modal-body">
    <p>Modal Body</p>
  </div>
  <footer>
    <a href="#" class="js-modal-close">Close Button</a>
  </footer>
</div>   

I'm not sure if this is the right approach.

I've been trying to add modal-box.html into function popup-modal(). I've also tried to enqueue modal-box.html but it gives an error message Uncaught SyntaxError: expected expression, got '<'

How can I load the html file as an external file into the single product page? If this is not the right way to do it, how can I add a modal box to the single product page?

Thanks

CodePudding user response:

Instead of is_singular( 'product' ) use woocommerce's own is_product()

For the modal, what about including it in the footer, also only on product pages, like this?:

function your_modal_footer(){
  if( !is_product() ){
     return;
  }
?>
<div id="popup" class="modal-box">  
  <header>
    <a href="#" class="js-modal-close close">×</a>
    <h3>Modal Title</h3>
  </header>
  <div class="modal-body">
    <p>Modal Body</p>
  </div>
  <footer>
    <a href="#" class="js-modal-close">Close Button</a>
  </footer>
</div>
<?php
}
add_action('wp_footer', 'your_modal_footer');

I would add a style="display:none;" to the popup div and then make it visible onclick of the popup's trigger.

  • Related