Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress enqueue script issues ("$ is not defined")

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?

like image 959
LachlanF Avatar asked Sep 29 '10 00:09

LachlanF


1 Answers

The only way how I've fixed this issue was by replacing all "$" with "jQuery" in the script that you're including.

In your case your new script will look like this:

jQuery(document).ready(function(){
    jQuery(".btn-slide").click(function(){
        var jQuerymarginLefty = jQuery("#slide-panel");
    jQuerymarginLefty.animate({
      marginLeft: parseInt(jQuerymarginLefty.css('marginLeft'),10) == 0 ? 
        jQuerymarginLefty.outerWidth() :
        0
                        });
                                    });
                            });
like image 87
Mike Avatar answered Sep 19 '22 16:09

Mike