Skip to content
Advertisement

How can initialize Fancybox into WordPress with a separate .js file properly?

I did a search and found this method here using wp_add_inline_script. And it works.

But what if I wanted to keep my initialization script into an other .js file? That’s what I wanted at first. How I can I load correctly? I tried this but the loading of my init-fancybox must be too early because I get an error.

(my init-fancybox script is not the problem because it works when it is loaded correctly using wp_add_inline_script)

function fancybox_enqueues() { 

    wp_register_script( 'fancybox', get_theme_file_uri( '/assets/js/jquery.fancybox.min.js' ), array('jquery'), '3.5.7', true);
    wp_register_script( 'init-fancybox', get_theme_file_uri( '/assets/js/init-fancybox.js' ), array('jquery','fancybox'), '1.0', true);
    wp_register_style( 'fancybox-css', get_theme_file_uri( '/css/jquery.fancybox.min.css' ), '1.0');

    if ( is_singular( 'item' ) ) {
        wp_enqueue_script( 'jquery');
        wp_enqueue_script( 'fancybox' );
        wp_enqueue_script ('init-fancybox');
        wp_enqueue_style( 'fancybox-css' );
    }
}
add_action( 'wp_enqueue_scripts', 'fancybox_enqueues');

Here is the error I get TypeError: $ is not a function

And here is the init-fancybox.js

$('[data-fancybox="single-item__gallery"]').fancybox({
    buttons : [ 
        "zoom",
        "share",
        //"slideShow",
        "fullScreen",
        //"download",
        "thumbs",
        "close"
    ],
    thumbs : {
      autoStart : false
    }
  });

Advertisement

Answer

It seems jQuery is not loaded by the time your code is running. Try adding the following function around it to make sure jQuery exists before your code runs:

jQuery(document).ready(function ($) {

  // Your function goes here:
  $('[data-fancybox="single-item__gallery"]').fancybox({
    buttons: [
      "zoom",
      "share",
      //"slideShow",
      "fullScreen",
      //"download",
      "thumbs",
      "close"
    ],
    thumbs: {
      autoStart: false
    }
  });

});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement