Yetti Yetti - 1 month ago 5
HTML Question

Using jQuery with Flask

I have a problem using jQuery with Jinja2 + Flask-bootstrap and Flask framework. When I create:

<script>
$('#commentButton').click(function() {
alert('clicked');
});
</script>


I get the following error:


Uncaught ReferenceError: $ is not defined


I can see in Chrome dev tools, that jQuery library is received.

Answer

Flask-Bootstrap includes jQuery at the end of your body tag. If you try to reference it earlier on the page you will receive this error.

The easiest way to make sure your code is placed after jQuery is to override the template tag.

{% block scripts %}
    {{ super() }}

    <script>
        $('#commentButton').click(function() {
             alert('clicked');
         });
    </script>
{{ endblock }}