simplycountdown.js

repository·develop·Indexed 41 days ago

https://github.com/vincentloy/simplycountdown.js

A lightweight (<5KB), zero-dependency JavaScript countdown library for creating customizable countdown or count-up timers. Version 3.0.1 features TypeScript support, multiple built-in themes (Default, Dark, Cyberpunk, Circle, Losange), and a modern API compatible with ES Modules, CommonJS, and UMD. It provides a CountdownController for programmatically pausing, resuming, and updating timers, and supports flexible targeting via CSS selectors, DOM elements, or NodeLists.

Tokens
3.2K
Snippets
13
Records
13
Agent score
51%

What's inside simplycountdown.js

  1. Migrate from v1.x/v2.x to v3.x

    develop

    If you are upgrading from an older version of simplyCountdown.js, note that jQuery support has been removed. To maintain compatibility in jQuery-based projects, switch from the jQuery plugin syntax to the vanilla JavaScript syntax.

    Key changes in v3.x:

    • No jQuery dependency: Use vanilla JS instead of $(selector).simplyCountdown().
    • TypeScript: The source is now written in TypeScript for better type safety.
    • Module Formats: Distribution files now include ES, UMD, and CommonJS formats.
    • Build Tooling: The project has migrated from Gulp to Vite.
    // ❌ Old jQuery-compatible syntax (No longer supported)
    $('.some-countdowns').simplyCountdown(options);
    
    // ✅ New vanilla JavaScript syntax
    simplyCountdown('.some-countdowns', options);
  2. Basic Usage with simplyCountdown()

    develop

    To use the plugin, target an HTML element with a CSS selector and provide a configuration object. The plugin supports ES Modules, CommonJS, and UMD (Browser) formats.

    import simplyCountdown from "simplycountdown.js";
    
    // Target an element with class '.my-super-countdown'
    simplyCountdown(".my-super-countdown", {
        year: 2025,
        month: 12,
        day: 25,
    });
  3. Use built-in themes

    develop

    SimplyCountdown.js includes several pre-built themes. To use a theme, include its CSS file in your HTML and apply the corresponding class to your target element.

    ThemeCSS FileClass to Apply
    Defaultdist/themes/default.csssimply-countdown
    Darkdist/themes/dark.csssimply-countdown-dark
    Cyberpunkdist/themes/cyber.csssimply-countdown-cyber
    Circledist/themes/circle.csssimply-countdown-circle
    Losangedist/themes/losange.csssimply-countdown-losange

    Example Implementation:

    <link rel="stylesheet" href="path/to/themes/circle.css" />
    <div class="simply-countdown-circle"></div>
    <link rel="stylesheet" href="path/to/themes/default.css" />
  4. Configure simplyCountdown options

    develop

    The simplyCountdown function accepts a selector (string, DOM element, or NodeList) and a configuration object.

    Target Date (Required)

    • year: Target year [YYYY]
    • month: Target month [1-12]
    • day: Target day [1-31]
    • hours: Target hours [0-23]
    • minutes: Target minutes [0-59]
    • seconds: Target seconds [0-59]

    Words Customization

    • words: An object containing days, hours, minutes, and seconds. Each contains a root (string) and a lambda function (root, count) => string to handle pluralization.

    Display Options

    • plural: Boolean. Enable/disable pluralization.
    • inline: Boolean. If true, displays in a single line; if false, displays in blocks.
    • inlineSeparator: String. Separator used when inline is true.
    • enableUtc: Boolean. Use UTC time instead of local time.
    • zeroPad: Boolean. Add leading zeros to numbers (e.g., 05 instead of 5).
    • countUp: Boolean. Count up from target date instead of down to it.
    • removeZeroUnits: Boolean. Hide time units when they reach zero.
    • refresh: Number. Update interval in milliseconds.

    Styling Classes

    • inlineClass: Class for inline display.
    • sectionClass: Class for each time unit section.
    • amountClass: Class for number display.
    • wordClass: Class for word display.

    Event Handlers

    • onEnd: Callback when countdown ends.
    • onStop: Callback when countdown is stopped.
    • onResume: Callback when countdown is resumed.
    • onUpdate: Callback when countdown is updated.
    simplyCountdown(".my-super-countdown", {
        year: 2025,
        month: 12,
        day: 25,
        words: {
            days: {
                lambda: (root, count) => (count > 1 ? root + "s" : root),
                root: "day",
            },
            // ... other words
        },
        plural: true,
        inline: false,
        enableUtc: false,
        zeroPad: false,
        countUp: false,
        refresh: 1000,
        onEnd: () => {
            console.log("Countdown finished!");
        }
    });
  5. Install and import simplyCountdown.js

    develop

    SimplyCountdown.js can be integrated into your project using several different module systems depending on your environment:

    • ES Modules (Vite/Rollup/Modern Browsers): Use the default export.
    • CommonJS (Node.js): Use require() to import the module.
    • AMD: The library supports AMD loaders via define.
    • Browser (UMD/Global): If loaded via a <script> tag in a standard browser environment, the library is available on the global window.simplyCountdown object.
    // ES Module
    import simplyCountdown from 'simplycountdown.js';
    
    // CommonJS
    const simplyCountdown = require('simplycountdown.js');
    
    // Browser Global
    // <script src="path/to/simplycountdown.js"></script>
    // simplyCountdown.simplyCountdown({...});
  6. Support for different selector types

    develop

    The plugin is flexible with how you target elements. You can pass:

    1. A CSS selector string.
    2. A single DOM element.
    3. A NodeList (multiple elements).
    // CSS selector string
    simplyCountdown("#countdown", parameters);
    
    // Single DOM element
    simplyCountdown(document.getElementById("countdown"), parameters);
    
    // Multiple elements
    simplyCountdown(document.querySelectorAll(".countdown"), parameters);
  7. Control a countdown instance

    develop

    The simplyCountdown function returns a controller object that allows you to manipulate the active countdown instance.

    • pause(): Stops the countdown.
    • resume(): Resumes the countdown.
    • update(options): Updates the countdown parameters (e.g., changing the target date).
    const countdown = simplyCountdown("#mycountdown", {
        year: 2025,
        month: 1,
        day: 1
    });
    
    // Control the instance
    countdown.pause();
    countdown.resume();
    countdown.update({ year: 2026, month: 1, day: 1 });
  8. Configure CountdownParameters

    develop

    The CountdownParameters interface defines the configuration for a countdown instance. It controls the target date, formatting (words, pluralization, inline display), styling (CSS classes), and lifecycle callbacks.

    Key configuration groups include:

    • Target Date: year, month, day, hours, minutes, seconds.
    • Word Formatting: The words object allows customizing how time units are labeled using WordConfig (providing a root string and a lambda function for pluralization logic).
    • Display Styles: inline (boolean), inlineSeparator (string), zeroPad (boolean), and various CSS class overrides like inlineClass, sectionClass, amountClass, and wordClass.
    • Lifecycle Callbacks: onEnd (required), onStop, onResume, and onUpdate (receives Partial<CountdownParameters>).
    const params: CountdownParameters = {
      year: 2025,
      month: 12,
      day: 25,
      hours: 0,
      minutes: 0,
      seconds: 0,
      words: {
        days: { root: 'day', lambda: (root, n) => n === 1 ? root : `${root}s` },
        hours: { root: 'hour', lambda: (root, n) => n === 1 ? root : `${root}s` },
        minutes: { root: 'minute', lambda: (root, n) => n === 1 ? root : `${root}s` },
        seconds: { root: 'second', lambda: (root, n) => n === 1 ? root : `${root}s` }
      },
      plural: true,
      inline: false,
      enableUtc: false,
      onEnd: () => console.log('Countdown finished!')
    };
  9. Locate library files in the /dist directory

    develop

    When using the compiled library, all production-ready assets are located in the /dist directory. This includes the core JavaScript logic in both ES module and UMD formats, along with their corresponding source maps for debugging. Themes are also provided here in both minified and unminified CSS formats.

    dist/
    ├── themes/
    │   └── ALL BUILT THEMES, both minified and unminified
    ├── simplyCountdown.js
    ├── simplyCountdown.js.map
    ├── simplyCountdown.umd.js
    └── simplyCountdown.umd.js.map
  10. Use the CountdownController API

    develop

    The CountdownController interface provides methods to programmatically manage a running countdown. If you initialize multiple countdowns, you may receive a CountdownControllerArray which extends the standard array with collective control methods.

    Available methods:

    • stopCountdown(): Pauses the countdown.
    • resumeCountdown(): Resumes a paused countdown.
    • updateCountdown(newParams: Partial<CountdownParameters>): Updates the countdown configuration (e.g., changing the target date) without a full restart.
    • getState(): Returns the current CountdownState, including isPaused, the active interval ID, and the targetDate.
    // Assuming 'controller' is an instance of CountdownController
    controller.stopCountdown();
    
    const state = controller.getState();
    console.log(state.isPaused); // true
    
    controller.updateCountdown({ year: 2026 });
    controller.resumeCountdown();