views:

55

answers:

2

Hopefully this one is a pretty easy fix for you guys :)

I am building a wordpress theme, and had previously been fairly poorly calling the jquery script in the html head tag. This was causing some loading lag in Opera though, which I suspect is because I was trying to load jquery simultaneously in two ways... anyway I'm now doing it properly in the functions.php file, but my further script that depend on jquery is not playing nice.

here's the snippet of how I'm now enqueuing jquery and my script (for a sliding panel):

add_action('init', 'my_init');
function my_init() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', false, '1.4.2', true);
        wp_enqueue_script('jquery');
        wp_enqueue_script('slide_script', get_template_directory_uri() . '/scripts/slide.js');
        echo "alert( 'Hello Admin!' );";
    }
}

and here's my sliding panel script:

$(document).ready(function(){
    $(".btn-slide").click(function(){
        var $marginLefty = $("#slide-panel");
    $marginLefty.animate({
      marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ? 
        $marginLefty.outerWidth() :
        0
                        });
                                    });
                            });

this was all working a treat when I was just calling jquery in the head tags and then placing this script in script tags directly afterwards, but now firebug shows it throwing "$ is not defined" and changing $ to jquery produces "jquery is not defined"... can anyone help?

+1  A: 

Use jQuery with a capital Q instead of $ to make it work. Wordpress usually includes a script which calls jQuery.noConflict() at the end, leaving $ undefined. The result should be something like this:

jQuery(function($) { //jQuery passed in as first param, so you can use $ inside
  $(".btn-slide").click(function(){
    var $marginLefty = $("#slide-panel");
    $marginLefty.animate({
      marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ? $marginLefty.outerWidth() : 0
    });
  });
});
Nick Craver
no good unfortunately, still getting "jQuery is not defined"
LachlanF
@LachlanF - is it possible it's getting included *before* jQuery is included in the page?
Nick Craver
A: 

make sure you indicate your script is dependent on jQuery by doing this in the wp_enqueue -> wp_enqueue_script('slide_script', get_template_directory_uri() . '/scripts/slide.js', array('jquery'));

Notice the array('jquery') That indicates that your script is dependent on jQuery.

Darren
magic! thanks very much :D
LachlanF
If you could accept this answer, i'd appreciate it
Darren