0

i have this code:

{% for review in reviews %}
   <div>
     {{ review.content }}
       by {{ review.username }}
       - timeDifference("{{ review.date_submitted }}")
   </div>
{% endfor %}

on the 5th line is a js function timeDifference that will return time difference in text, I want to insert js function there, how do I do that?

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

2 Answers2

0

Execute Js function like that is not possible. And what possible is during onload time execute the javascript function and do DOM manipulation.

In Html

<-- In for loop -->
<div onload="timeDifference( {{ review.id }}, {{ review.date_submitted }} );">
  <p id="timeDifferenceElement{{ review.id }}"></p>
</div>

In Javascript

function timeDifference(id, date_submitted) {
  const timeDifferenceElement = document.getElementById("timeDifferenceElement" + id)
  // Do calculation
  ---
  timeDifferenceElement.innerHTML = "something from the calculation"
}
Raja Simon
  • 10,126
  • 5
  • 43
  • 74
0

this is the solution that worked for me, inspired by Raja Simons' answer and How to add onload event to a div element?:

<div id="review{{review.id}}">
   {{ review.content }} by {{ review.username }}
     -
   <p id="timeDifferenceElement{{ review.id }}"></p>
   <script type="text/javascript">
    timeDifferenceForDate( '{{ review.id }}', '{{ review.date_posted }}' );
   </script>

gpbaculio
  • 5,693
  • 13
  • 60
  • 102