javascript - Using jquery to run code when django document is ready -


i building django admin site , using javascript , jquery (2.0.3) add functionality forms.

i importing scripts page 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 placed following code @ end of project.js:

function trycustomiseform() {     // ... }  $(document).ready(trycustomiseform);  

unfortunately results in uncaught typeerror: undefined not function exception on last line.

i tried alternative syntaxes of ready() without more luck.

lastly explored change_form.html template , found inline javascript:

<script type="text/javascript">     (function($) {         $(document).ready(function() {             $('form#{{ opts.model_name }}_form :input:visible:enabled:first').focus()         });     })(django.jquery); </script> 

i able modify suit needs , project.js ends with:

(function($) {     $(document).ready(function() {         trycustomiseform();     }); })(django.jquery); 

while results in correct behaviour i don't understand it.

this leads question: why did first approach fail? , second approach doing?

it's hard tell code you've posted, looks $ variable not assigned jquery in template; hence $() construct threw undefined function error.

the reason latter works because puts closure around domready handler, passes in django.jquery, assume noconflict jquery assigned variable template, , assigns $ within scope of that:

(function($) { // < start of closure     // within block, $ = django.jquery     $(document).ready(function() {         trycustomiseform();     }); })(django.jquery); // passes django.jquery parameter closure block 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -