$ not defined using jQuery in WordPress

I know that jQuery is loaded, because I can switch out the $ for ‘jQuery’ and everything behaves as expected, but this will be a messy script if I can’t fix this

This script:

jQuery(document).ready(function(){
    $("ul.vimeo_desc_feed li a").click(function(){
        alert($(this).attr('href'));
        return false;
    })
});

Produces the error $ is not a function

This script:

jQuery(document).ready(function(){
    jQuery("ul.vimeo_desc_feed li a").click(function(){
        alert(jQuery(this).attr('href'));
        return false;
    })
});

works fine.

3

You can wrap your javascript inside a self-invoking function, then pass jQuery as an argument to it, using $ as the local variable name. For example:

(function($) {
  $(document).ready(function(){
    $("ul.vimeo_desc_feed li a").click(function(){
      alert($(this).attr('href'));
      return false;
    })
 });
}(jQuery));

should work as intended.

If I remember correctly the WP-supplied version of jQuery (the one you get if you wp_enqueue_script('jquery')) puts jQuery in no-conflict immediately, causing $ to be undefined.

Leave a Comment