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.

link|improve this question

74% accept rate
feedback

2 Answers

up vote 6 down vote accepted

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.

link|improve this answer
aah, I see. I used to add it by hand, which explains why I have not come across this issue. – Mild Fuzz Oct 14 '10 at 15:46
feedback

You're almost there!

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

});

You have to pass a reference to jQuery as the $ function into your method or it won't work. If you just place a $ inside the first function() call as I did above, things will be working just fine.

link|improve this answer
1  
+1: That is more readable than putting jQueryat the end. – toscho Oct 14 '10 at 17:42
...but it isn't the standard way of doing an anonymous function. forum.jquery.com/topic/jquery-anonymous-function-calls – BryanH Oct 14 '10 at 23:55
2  
Yes and no. They're both considered "standard" ways of doing it. One creates a singleton class that has $ defined locally. The other just defines a handler for the document's ready event and passes the jQuery object into the handler as $. If you're trying to hook on to the ready event, the second method is more widely used. If you need jQuery for any other purpose (to hook on to $.browser for example), you'd use a singleton class. – EAMann Oct 15 '10 at 1:39
+1 for jQuery(document).ready(function($){... mor infos about jquery and WordPress can you also read on my post: wpengineer.com/2028/small-tips-using-wordpress-and-jquery . – bueltge Oct 15 '10 at 12:46
Thanks, found this helpful for something else I was working on. – Noel Tock Jan 22 '11 at 15:36
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.