Sterling Archer
Sterling Archer

Reputation: 22395

jQuery $ is not defined

Normally I would be able to figure this one out but this one has me trumped.

I inherited a project at work that is.. horrifying. I've cleaned it all up and everything, except for the javascript/jquery.

I have a simple document ready click alert("test") function running, (and it works??) in an external javascript file. If I include jQuery 1.9.0, the alert pops up twice (which according to the console it is being called somewhere.. so including it where I did seemed to be a duplicate).

So my question is what cases would cause jQuery to work, yet trigger the undefined $?

And .noConflict() is NOT being called.

The code is called here:

$(document).ready(function() {
    $("#contactSecondaryYes").click(function(){
        alert($(this).val());
    });
});

Upvotes: 0

Views: 147

Answers (2)

jeroenvisser101
jeroenvisser101

Reputation: 881

You might want to use an self-invocing anonymous function for this.

(function ($){
  // Use $ here all you want
})(jQuery);

What this does is create an anonymous function and call it immediately afterwards, with the jQuery as argument. Within this function, you can use jQuery. There are a lot of variations on this.

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

This can be one of two issues, both boiling down to the same issue: not referencing jQuery.

You either (I think yours is B):

A) Haven't referenced jQuery
B) Have another script file (possibly external) that uses jQuery syntax/functions but is referenced before your jQuery reference. Simply referencing jQuery first will remedy this issue.

Upvotes: 6

Related Questions