Odd jQuery behaviour in WP

Hey all,

So I’m using jQuery with WordPress for the first time. I have included the jquery file in my header.php file like this:


wp_enqueue_script('jquery');

which works a treat.

Then, after the wp_head(); function, I have written a very basic script:


<script type="text/javascript">
  $(document).ready(function() {
    $('.children').hide();
  });
</script>

It doesn’t run.

Now, if I look at the source code of the web-page, everything looks good.

On the console of Chrome, I get the following error message:

Uncaught TypeError: Property ‘$’ of object [object DOMWindow] is not a function

This is referring to the script that I have written. The jquery file runs fine.

Has anyone experienced something like this before? I haven’t a clue what’s happening here.

Many thanks,
Mike

Sorry to bump my own post, but I found the answer on the WP Codex…

jQuery noConflict wrappers
Note: The jQuery library included with WordPress loads in “no conflict” mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load.

In “no-confict” mode, the $ shortcut is not available and the longer jQuery is used. For example:


$(document).ready(function(){
     $(#somefunction) ...
});

Becomes:


jQuery(document).ready(function(){
    jQuery(#somefunction) ...
});

In order to use the default jQuery shortcut of $, you can use the following wrapper around your code:


jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

That wrapper will cause your code to be executed when the page finishes loading, and the $ will work for calling jQuery.

Big thanks !!