I'm trying to create a script with jQuery where it finds elements with the class "timeAgo" and replace its innerHTML with how long ago the time in the create attribute was. Here's what I have:
function timeAgo(time) {
var d = new Date();
var diff = Math.floor((d.getTime() - time)/1000);
if (diff >= 31536000) {
if (Math.floor(diff/31536000) == 1) {
return (Math.floor(diff/31536000) + " year ago");
} else {
return (Math.floor(diff/31536000) + " years ago");
}
} else if (diff >= 2592000) {
if (Math.floor(diff/2592000) == 1) {
return (Math.floor(diff/2592000) + " month ago");
} else {
return (Math.floor(diff/2592000) + " months ago");
}
} else if (diff >= 86400) {
if (Math.floor(diff/86400) == 1) {
return (Math.floor(diff/86400) + " day ago");
} else {
return (Math.floor(diff/86400) + " days ago");
}
} else if (diff >= 3600) {
if (Math.floor(diff/3600) == 1) {
return (Math.floor(diff/3600) + " hour ago");
} else {
return (Math.floor(diff/3600) + " hours ago");
}
} else if (diff >= 60) {
if (Math.floor(diff/60) == 1) {
return (Math.floor(diff/60) + " minute ago");
} else {
return (Math.floor(diff/60) + " minutes ago");
}
} else {
if (diff == 1) {
return (diff + " second ago");
} else {
return (diff + " seconds ago");
}
}
}
$(document).ready(function () {
$(".timeAgo").innerHTML(timeAgo($(".timeAgo").attr("create")));
}
But whenever I run the code with multiple instances of ".timeAgo", it sets all of them to the first instance of ".timeAgo". How do I make it so that it uses each separate instance?