2

I have this in my HTML body:

<script src="{% static "jquery/sessionExists.js" %}"></script>

{% if context.alreadyOnSession == 'YES' %}
    <h5 class="loginerror" onload="advSessionExists()">This session is already logged in</h5>
{% endif %}

These {} are django code.

sessionExists.js:

function advSessionExists(){
    console.log('Just checking if its triggered');
}

Also I tried by putting my JavaScript code raw in the HTML body with <script type=text/javascript></script>, and also I tried with onbeforeprint instead of onload but it is still not showing my JS method.

The <h5> is being showed, but not triggering my JS method.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Gonzalo Dambra
  • 891
  • 2
  • 19
  • 34

2 Answers2

3

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 (or h5) is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

Via - How to add onload event to a div element?


To invoke the function when your <h5> element has loaded, just call the function right after the <h5> element within your django if statement like this:

{% if context.alreadyOnSession == 'YES' %}

    <h5 class="loginerror">This session is already logged in</h5>

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

{% endif %}
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
0

Try add onload="advSessionExists() to script tag. Or write in your script window.addEventListener('onload', advSessionExists);

Staxaaaa
  • 154
  • 1
  • 10