How do I get the jQuery function show below to wait until the DOM has loaded before it's read? I thought that specifying "$(document).ready(function..." at the beginning of the function declaration would do the trick but when my page executes, the function doesn't work and I can see the message "Uncaught ReferenceError: $ is not defined" in my browser's developer console.
This is my base template:
# base.html
<!DOCTYPE html>
<html>
...
<body>
{% block page_container %} {% endblock %}
...
<script src="https://code.jquery.com/..."></script>
<script src="js/bootstrap.min.js"></script>
...
</body>
</html>
This Django template extends (is enclosed by) the base template:
# upload_file.html
{% extends base.html %}
(HTML for form ...)
<label class="btn btn-success btn-file">
Select Photo <input type="file" name="photo" style="display: none;">
</label>
(more HTML...)
<script>
$(document).ready(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
});
</script>
Of course, if I move the script tag that calls jQuery up inside the block in my base template, the function executes. However, I'd prefer to keep my jQuery script element at the bottom of my base template as is illustrated in the Bootstrap documentation. Is there a way to get this function to work if jQuery is referenced after the function that calls it in my page?
Thanks.
-- FOLLOW-UP --
I credited fyrb with the answer since he answered first and I ended up doing what he proposed, but I appreciated the other answers too. I'm adding links to some good posts on this subject below for the benefit of others who have this question. There are some good performance reasons for putting your jquery call at the end of the page as will be seen in these articles.
- Stop paying your jQuery tax
- Should Jquery code go in header or footer?
- When do you choose to load your javascript at the bottom of the page instead of the top?
- why javascript runs when at bottom of page or sometimes from top of page
- pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
- $(document).ready equivalent without jQuery