SamPassmore
SamPassmore

Reputation: 1365

Javascript is not executing when javascript

I have created a simple javascript function to run in django that automatically changes text within a svg file.

The function works fine if I run it inside the webpage console. But nothing inside the script tags will run and I can't figure out why. Looking at the source the template tag is importing the data correctly and the javascript file is found. But nothing runs inside, not even code unrelated to the function - you can see the console.log code I have added.

I am quite new to django and website development, so it is unclear to me where I shoud be looking for why this isnt' executing - is there somewhere that errors should be arising?

home.html

{% extends 'kb/base.html' %}
{% load static %}

{% block extrahead %}

    <link rel="stylesheet" href="{% static 'css/kb.css' %}">



    <script type="text/javascript" src="{% static "js/fillKinshipDiagram.js" %}">
            console.log(4 + 10);
            var terms = {{ terms|safe }};
            window.onload = function() {
                main(terms);
            };
    </script>

{% endblock %}


{% block content %}

<div class="home-content">
    <div class="kinshipdiagram-container">
        <object type="image/svg+xml" data="{% static "img/diagrams/nuclear_diagram.svg" %}" id="kinshipdiagram" width="50%" height="50%"></object>
    </div>
</div>
{% endblock %}

fillKinshipDiagram.js

function main(terms){
    var svgDocument
    svgObject = document.getElementById('kinshipdiagram');
    svgDocument = svgObject.contentDocument;

    for (var i = 0; i < terms.length; i++){
        var kincode = terms[i].parameter_id
        text = svgDocument.getElementById(kincode)
        if (text != null){
            text.textContent = terms[i].form;
            text.style.fontSize = "20px"
        }
}

Upvotes: 0

Views: 139

Answers (1)

xdeepakv
xdeepakv

Reputation: 8125

There should be two different script tags. One to include external script js/fillKinshipDiagram.js, other is to add in-page script.

<script type="text/javascript" src="{% static "js/fillKinshipDiagram.js" %}"></script>
<script type="text/javascript" >
  console.log(4 + 10);
  var terms = {{ terms|safe }};
  window.onload = function() {
      main(terms);
  };
</script>

Upvotes: 3

Related Questions