Last active
August 29, 2015 14:14
-
-
Save AlexArchive/00ba4035c248f1f197c4 to your computer and use it in GitHub Desktop.
ago.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
var pluginName = 'ago'; | |
$.fn[pluginName] = function() { | |
return this.each(function() { | |
var element = $(this); | |
updateTitle(element); | |
}); | |
}; | |
function updateTitle(element) { | |
var dateString = element.attr("datetime"); | |
var date = new Date(dateString); | |
var since = timeSince(date); | |
element.attr("title", since + " ago"); | |
} | |
// http://stackoverflow.com/a/3177838/2015959 | |
function timeSince(date) { | |
var seconds = Math.floor((new Date() - date) / 1000); | |
var interval = Math.floor(seconds / 31536000); | |
if (interval > 1) { | |
return interval + " years"; | |
} | |
interval = Math.floor(seconds / 2592000); | |
if (interval > 1) { | |
return interval + " months"; | |
} | |
interval = Math.floor(seconds / 86400); | |
if (interval > 1) { | |
return interval + " days"; | |
} | |
interval = Math.floor(seconds / 3600); | |
if (interval > 1) { | |
return interval + " hours"; | |
} | |
interval = Math.floor(seconds / 60); | |
if (interval > 1) { | |
return interval + " minutes"; | |
} | |
return Math.floor(seconds) + " seconds"; | |
} | |
}(jQuery)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$( document ).ready(function() { | |
$("time[datetime]").ago(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment