Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
Yetti Avatar asked Dec 20 '22 10:12

Yetti


1 Answers

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 %}
like image 58
dirn Avatar answered Jan 13 '23 18:01

dirn