I've go a small application that display live feeds and uses livestamp + moment to update the time in a format similar to what Stackoverflow does to its messages.
Now I would like to change it slightly to show things past 24hs in a different format.
I found this thread which was exactly what I was looking for
Unhappily it doesn't work for my case, an example of my element is as follow:
<div id="container">
<div something else>
</div>
<div id="feed">
<div class="timestamp" title="Less than 1 minute ago">7 minutes ago</div>
</div>
</div>
Of course the above is after livestamp has modified it, since my feed is added dynamically with jquery/ajax.
So considering the above I changed that code as follow:
$('.timestamp').on('change.livestamp', function(event, from, to)
{
event.preventDefault(); // Stop the text from changing automatically
// Get the original timestamp out of the event
var originalTS = event.timeStamp;
// Make a new moment object to compare the timestamp to
var newDate = moment();
// Use moment's .diff method to get the ms difference between timestamps
var delta = newDate.diff(originalTS);
// If the difference is less than a day's worth of ms
if (delta < 86400000){
// Use formatted text provided by the change event
console.log("if: " + newDate.format("dddd M/D/YYYY"));
$(this).html(to);
}
else {
// Format the moment object with whatever moment format you want
console.log("Else: " + newDate.format("dddd M/D/YYYY"));
$(this).html( newDate.format("dddd M/D/YYYY") );
}
}).livestamp();
And added it inside my $(document).ready(function()
, however due to my .timestamp being dynamically added(I believe), the onchange never triggers.
If I instead use #container
, it triggers, and I assume with that I would have to iterate thru all the items to manually update it and the problem is, I can't, because the timestamp is only present for 1 item(not per item) in this case, thus I won't be able to know which timestamp to update for the rest as livestamp removes it after the first iteration.
Is there any way to make it properly recognize the dynamic elements and do the onchange per element, as in the proposed above code in this scenario? or am I overlooking something?
Or maybe its possible to set the custom formatting directly on livestamp.js?
Something like:
var newDate = moment();
var delta = newDate.diff(to);
if (delta >= 86400000)
{
to = to.format("dddd M/D/YYYY");
}