Roman Roman - 5 months ago 22
Javascript Question

JavaScript onload not recognized in extended html python flask

I use a

basic.html
in my flask application which loads all needed ressources like footer navbar etc., all my other html sites extend this
basic.html


In my
main.js
I created a simple function:

function fun() {
alert("we have fun");
}


I load my files like this in the
basic.html
:

<script type=text/javascript src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>

<script type=text/javascript src="{{ url_for('static', filename='js/bootstrap.js') }}"></script>

<script type=text/javascript src="{{ url_for('static', filename='js/main.js') }}"></script>


Now I want to use this function in my
page.html
which extends the
basic.html
:

{% extends "basic.html" %}

{% block content %}

<div class = "container" onload="fun()">
<p> Test </p>
</div>

{% endblock %}


Sadly nothing happens, but if I use the
onload="fun()"
in the
basic.html
itself it works.

So how do I resolve this?

This is a very simplified version of one of my previous question, due to the fact that I am sitting on this since 4 hours I think I know what causes the issue but I cant solve it and all solutions I found do not work.

Here is my previous question:
question

I think that
onload="fun()"
is called before jQuery is even load or my main.js but I am still not 100% sure if this causes the error and I cant find a solution

Answer

The problem is simple. You can't attach onload to a div.

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

Adding the script tag immediately after the div element will cause it to fire as soon as the div is rendered. So this will perfectly work:

{% extends "basic.html" %}
{% block content %}

<div class="container">
<p> Test </p>
</div>

<script type="text/javascript">
fun();
</script>

{% endblock %}

Read more here: How to add onload event to a div element?

Instead of appending a script tag with the function call, you can use another solution explained here: http://stackoverflow.com/a/17071878/4395646