Using jquery to run code when django document is ready

django, events, html, javascript, jquery

Solution

It's hard to tell from the code you've posted, but it looks like the `$` variable is not assigned to jQuery in your template; hence the `$()` construct threw the `undefined function` error.

The reason the latter works is because it puts a closure around your DOMReady handler, which passes in `django.jQuery`, which I assume to be the `noConflict` jQuery assigned variable from your template, and assigns it to the `$` within the scope of that:

(function($) { // < start of closure
    // within this block, $ = django.jQuery
    $(document).ready(function() {
        tryCustomiseForm();
    });
})(django.jQuery); // passes django.jQuery as parameter to closure block

Problem

I am building a django admin site and am using javascript and jquery (2.0.3) to add some extra functionality to the forms. I am importing the scripts into my page like this: ``` <html> <head> <script type="text/javascript" src="/static/admin/js/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/project/js/project.js"></script> </head> <!-- ... --> </html> ``` At first I placed the following code at the end of `project.js`: ``` function tryCustomiseForm() { // ... } $(document).ready(tryCustomiseForm); ``` Unfortunately this results in an `Uncaught TypeError: undefined is not a function` exception on the last line. I then tried the alternative syntaxes of `ready()` without any more luck. Lastly I explored the `change_form.html` template and found this inline javascript: ``` <script type="text/javascript"> (function($) { $(document).ready(function() { $('form#{{ opts.model_name }}_form :input:visible:enabled:first').focus() }); })(django.jQuery); </script> ``` I was able to modify it to suit my needs and now my `project.js` ends with: ``` (function($) { $(document).ready(function() { tryCustomiseForm(); }); })(django.jQuery); ``` While this results in the correct behaviour I don't understand it. This leads to my question: Why did my first approach fail? And what is the second approach doing?

Original source