Issue
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.
Solution
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>
Answered By - epascarello
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.