NathanKTC
NathanKTC

Reputation: 81

A simple custom Lightbox failing

I've built a simple lightbox, easy enough with organic pages, I have the code working on codepen and a local file, however the second I throw it in wordpress it isn't working, maybe you guys can help me find out why.

Basically i have two elements, the smaller image, and the fullsized lightbox.

The jquery function is

jQuery(document).ready(function($) {
 $('.feature-single-image').live("click", function(){
   $('.lightbox-bg').show();
 });
 $('.lightbox-bg').live("click", function(){
   $('.lightbox-bg').hide();
 });
});

my enqueue script is

function wpb_adding_scripts() {
 wp_register_script('lightbox', get_template_directory_uri() . '/js/lightbox.js', array('jquery'),'1.1', true);
 wp_enqueue_script('lightbox');
} 

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); 

The jquery script is saved in the child theme js folder.

I can't image why it isn't working but would love some help figuring this out.

Also

I should also mention the script with the .live( bit was a suggestion i saw on a similar post, but did not work for me. The original script was

 jQuery(document).ready(function($) {
  $('.feature-single-image').click(function() {
    $('.lightbox-bg').show();
  });
  $('.lightbox-bg').click(function() {
    $('.lightbox-bg').hide();
   });
 });

Upvotes: 0

Views: 130

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

Actually it looks like you might have to change a few settings in Wordpress to use jQuery like you want, see How do I add a simple jQuery script to WordPress?

Original answer:

You likely have another library somewhere that is setting $ to be an alias for something other than jQuery, try using an Immediately-Invoked Function Expression (IIFE) and passing in jQuery as $:

(function ($) { // IIFE passing in jQuery as $, inside the scope of this function $ is an now alias for jQuery, all of your jQuery code should be inside this function or one like it 

    $(document).ready(function () {
        $('.feature-single-image').live("click", function () {
            $('.lightbox-bg').show();
        });
        $('.lightbox-bg').live("click", function () {
            $('.lightbox-bg').hide();
        });
    });

}(jQuery)); // pass in jQuery

Of you could just change all of your $s to jQuery which would also work. I prefer the IIFE though.

Upvotes: 1

Related Questions