Unlocking the Power of Time Manipulation with Timeago js for Enhanced User Experience

Introduction to timeago.js

Timeago.js is a lightweight, simple, and efficient JavaScript library that allows you to format date strings into just-now, minute-ago, hour-ago, etc. It’s extremely useful for applications that continuously update the UI with real-time information without needing to reload the entire page.

Getting Started with timeago.js

To use timeago.js, you first need to include it in your project. You can either download it or include it via a CDN:


  <script src="https://cdn.jsdelivr.net/npm/timeago.js/dist/timeago.min.js"></script>

Basic Usage

Here’s how to get started with the basic usage of timeago.js:


  <span class="timeago" datetime="2023-10-01T12:24:00Z"></span>
  <script>
    timeago.render(document.querySelectorAll('.timeago'));
  </script>

Advanced Usage and API Examples

timeago.js includes multiple useful APIs to customize and manipulate time display as per your requirements. Here are some examples:

1. Render Specific Time Elements

Only apply the timeago transformation to specific elements:


  const nodes = document.querySelectorAll('.my-timeago');
  timeago.render(nodes);

2. Setting Locale

Timeago.js supports i18n. Here’s how to change the language setting:


  timeago.render(document.querySelectorAll('.timeago'), 'es');

3. Updating Timestamps

To update timestamps automatically:


  const instance = timeago();
  instance.render(document.querySelectorAll('.timeago'));

4. Canceling Updates

To stop timeago from updating timestamps:


  instance.cancel();

5. Using Custom Formatters

You can define your custom formatter:


  function customFormatter(number, index, totalSec) {
    return [
      ['just now', 'right now'],
      ['%s seconds ago', 'in %s seconds'],
      ['1 minute ago', 'in 1 minute'],
      // Add more custom time formats here
    ][index];
  }
  timeago.render(document.querySelectorAll('.timeago'), customFormatter);

Practical App Example

Let’s create a simple app that uses the above examples:


  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timeago.js Example</title>
    <script src="https://cdn.jsdelivr.net/npm/timeago.js/dist/timeago.min.js"></script>
  </head>
  <body>
    <h1>Recent Updates</h1>
    <p class="timeago" datetime="2023-10-01T12:24:00Z"></p>
    <script>
      timeago.render(document.querySelectorAll('.timeago'), 'en_US');
    </script>
  </body>
  </html>

Using timeago.js, we have dynamically changed the timestamps to automatically update and show recent updates in your preferred format and language.

Hash: f859654ed5936e123370f13c1c58bf994b3e5546faa91a4f647ae849d7e1bf3b

Leave a Reply

Your email address will not be published. Required fields are marked *