Kyle Torti Kyle Torti - 2 months ago 6
HTML Question

Using "time ago" Javascript function within HTML

I'm using the humanized_time_span from http://github.com/GrouchPotato/js_humanized_time_span

For a project I'm working on, I need a "time ago" time stamp for a list of "recent posts". My question is, can I include the humanized_time_span script within my HTML (it has to be that way, I can't use it as an external file) and how do I call the function within the HTML body? I'm pretty new with JS, so please explain in detail.

I have a UL list of these "posts" and I need to include the time stamp out beside each post.

<ul>
<li class="list-group-item"><a href="#"><strong>This is a random post</strong></a></li>
<li class="list-group-item"><a href="#"><strong>This is a random post 2</strong></a></li>
<li class="list-group-item"><a href="#"><strong>This is a random post 3</strong></a></li>
<li class="list-group-item"><a href="#"><strong>This is a random post 4</strong></a></li>
</ul>


Currently, I have the code from the github repo at the end of my HTML element between script tags, but I don't know how to use that script in the HTML.

Answer

So you would need to select the elements and run the function and replace the text.

So on document.ready or window onload you would need to select the elements, read the text, and call the function, and replace the text with what was returned.

var lis = document.querySelectorAll("li strong");  //select the elements
for (var i = 0; i < lis.length; i++) {  //loop over the HTML collection
  var li = lis[i],  //reference the current element of the collection
      text = li.innerHTML,  //read the text (could use textContent)
      result = humanized_time_span(text);  //run the function
  li.innerHTML = result;  //replace the text with the result returned from calling the function
}
<script src="https://rawgit.com/GrouchPotato/js_humanized_time_span/master/humanized_time_span.js"></script>

<ul>
  <li><strong>2016/09/13 11:00:00</strong>
  </li>
  <li><strong>2016/09/12 11:00:00</strong>
  </li>
  <li><strong>2016/09/11 11:00:00</strong>
  </li>
</ul>