I’m trying to remove <li> elements if they have been around longer than a minute. Each <li> contains an <a> element that has a data-created-at attribute. This created_at value was stored server side in a database.
When the page loads, it displays records from the databas.
<ul id="foobar">
<% @foos.each do |foo| %>
<li><%= link_to 'Foobar', '#', :'data-created-at' => foo.created_at.to_i %></li>
<% end %>
</ul>
My JS is trying to compare the system’s (browser, not server) time before it removes the <li> element:
$(document).ready(function(){
setInterval(function() {
$('#foobar a').each(function() {
if(new Date().getTime() - $(this).data('created-at') >= 60000) {
// It's been a minute
$(this).parents('li').fadeOut()
}
});
}, 10000); // 10 seconds
});
It’s a problem, because I need JS to dynamically remove any <li> elements. Since Date().getTime() is based on the browser / system. It’s a bit inconsistent if its dealing with the created_at value rendered from the server.
Any ideas how I can get this to work?
Yes @Lilina has a good approach. Insert the timestamp as a hidden input at the end of HTML document. This ensures it’s loaded last. Then add a document ready handler to calculate the offset between browser time and system time (from the hidden input tag). Apply this offset to all created-at attributes.