Alex Rivera | Logout

Difficulty with Django and jQuery (why is $ undefined in the admin app?)

Asked 2011-01-17T01:29:28.327
14

It's been a while since I worked with jQuery; I think I'm making a stupid mistake.

Here is a Django widget:

class FooWidget(Widget):

    # ...

    class Media:
        js = ('js/foowidget.js',)

Here is the .js file:

alert("bar");

$(document).ready(function() {
  alert("omfg");
  $('.foo-widget').click(function() {
    alert("hi");
    return false;
  });
});

alert("foo");

The only alert() that fires is the first. Do I have a stupid syntax error or something?

Also, if some other included script on the page redefines $(document).ready, do I have to worry about it? I'm guessing that subsequent definitions will override mine, so it's safer for subsequent definitions to do something like:

$(document).ready(function() {
    document.ready()
    // real stuff
});

jQuery is already included in the page by the time foowidget.js is.

Update: Based on @lazerscience's link, I tried the following instead, but it still fails just as before:

alert("bar");

$(function() {
  alert("omfg");
  $(".set-widget").click(function() {
    alert("hi");
    return false;
  });
});

alert("foo");

Update 2: Curiously, when I do:

alert($);

I get "undefined". This suggests that jQuery is actually not initialized. This confuses me, because the <head> includes:

<script type="text/javascript" src="/media/js/jquery.min.js"></script>
<script type="text/javascript" src="/media/js/jquery.init.js"></script>
<script type="text/javascript" src="/media/js/actions.min.js"></script>
<script type="text/javascript" src="/static/js/foowidget.js"></script>

Doesn't putting my script after the jQuery scripts ensure that $ will be defin

Edit
Report

3 Answers

31

Adding this to the top of my .js file fixes it:

var $ = django.jQuery;

I'm not sure how to remove the jquery.init.js file, given that my project doesn't contain any scripts that use $ for something other than jQuery.

answered 2011-01-17T17:11:42.940
2

Use the Firebug or Web Inspector JS console and type $ and/or jQuery. That's the simplest way to find out if the library has been loaded correctly. In the unlikely case, that only jQuery is defined, you can wrap your script into it's own scope:

(function($){
    // your code here…
})(jQuery);

If nothing is defined at the console, the problem is most likely with the file and I'd try AndiDog's approach to see if there's anything loaded at all.

answered 2011-01-17T08:21:55.980
-1

You probably forgot to include {{ form.media }} in your template.

answered 2011-01-17T10:30:59.647

Your Answer