FlipClock.js - Documentation

Getting Started

Installation

FlipClock.js can be included in your project using several methods:

1. Download: Download the latest release from the GitHub repository and include the flipclock.js file in your project. You’ll also likely need the CSS file, flipclock.css.

2. CDN: Use a CDN like jsDelivr:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flipclock@0.7.8/dist/flipclock.css">
<script src="https://cdn.jsdelivr.net/npm/flipclock@0.7.8/dist/flipclock.min.js"></script>

Remember to replace 0.7.8 with the desired version number if needed. Check the GitHub repository for the most up-to-date version.

3. npm: If you’re using npm, install FlipClock.js via:

npm install flipclock

Then, include the necessary files in your project as you would with any other npm package. You may need to adjust your build process to handle the inclusion of the CSS file appropriately.

Basic Usage

After including the necessary CSS and JavaScript files, you can initialize a FlipClock instance with a simple JavaScript command:

<div class="clock"></div>
<script>
  var clock = new FlipClock($('.clock'), 10, {
    clockFace: 'MinuteCounter' //Or 'Counter', 'HourlyCounter', 'DailyCounter'
  });
</script>

This code creates a FlipClock instance that counts down from 10 seconds. The first argument is a jQuery selector for the clock’s container element. The second argument is the starting value (in seconds in this case). The third argument is an object containing optional settings. clockFace determines which clock face style to use.

For other clock faces (like hours, minutes, days, etc), adjust the starting value and the clockFace accordingly. Refer to the documentation for a complete list of options and available clock faces.

Running the Example

FlipClock.js includes example code to help you get started. You can find this example code within the downloaded package or at the GitHub repository.

To run the example:

  1. Download: Download the FlipClock.js package.
  2. Open index.html: Open the index.html file located within the example directory of the downloaded package in your web browser. This HTML file includes the necessary CSS and JavaScript, and showcases the various options available within FlipClock.js

This will display a working FlipClock displaying the currently available examples. You can examine the source code in the index.html and the JavaScript files to better understand how to implement the various features. Remember to adjust file paths if you moved the files after downloading the package.

Core Concepts

Clock Creation

Creating a FlipClock instance involves several key steps:

  1. Include necessary files: Ensure that both the FlipClock CSS (flipclock.css) and JavaScript (flipclock.js) files are correctly included in your HTML document’s <head> section. This can be done via direct file inclusion, a CDN, or a package manager like npm, as described in the “Getting Started” section.

  2. Create a container element: In your HTML, create a <div> element (or other suitable container) that will hold the FlipClock. This element should have a unique ID or class for easy selection with jQuery. For instance: <div id="clock"></div>.

  3. Initialize FlipClock: Use the FlipClock constructor to create a new clock instance. The constructor takes at least two arguments:

    Optional arguments can be passed as a third parameter to customize the clock’s appearance and behavior (see below).

    var clock = new FlipClock($('#clock'), 120, {
        clockFace: 'MinuteCounter', // Specify the clock face
        autoStart: false,            // Optional: start the clock automatically (default true)
        // ... other options
    });
  4. Start the clock (if necessary): If autoStart is set to false in the options, you’ll need to manually start the clock using the start() method:

    clock.start();

Time Formats

FlipClock.js offers several pre-built clock faces (clockFace) that determine the time format displayed:

You cannot directly customize the displayed time format beyond these pre-defined options without modifying the underlying code. If you need a different format, you might need to create a custom clock face.

Event Handling

FlipClock.js provides several events you can listen for to respond to changes in the clock’s state. These are typically handled using jQuery’s .on() method with the clock instance as the context:

Remember to replace clock with your actual FlipClock instance variable. The specific data passed to the event handlers might vary depending on the event. Consult the documentation for detailed information on each event and its associated data.

Customization

Appearance Customization

FlipClock.js offers several ways to customize the appearance of your clock beyond the pre-defined clock faces. While it doesn’t offer extensive direct styling options for individual components, you can achieve substantial customization through CSS.

The primary method for customizing the appearance is by overriding the default CSS provided in flipclock.css. You can create a separate stylesheet or modify flipclock.css directly. Target specific classes within the generated HTML structure to style individual elements like digits, separators, and the overall clock container. Inspect the HTML generated by FlipClock using your browser’s developer tools to identify the classes you need to target.

For instance, to change the background color of the clock digits, you might find a class like .flip-clock-active or a more specific class related to a particular digit’s state (e.g., .flip-clock-dot-top). Use your browser’s developer tools to inspect and find the right class names to target. Then, apply your CSS rules accordingly. For example:

.flip-clock-dot { /*Adjust class to target specific element*/
  background-color: #FF0000; /*Example - change to your desired color*/
}

Remember that the class names might slightly vary depending on the clock face used and the version of FlipClock.js.

Font and Color Settings

Font and color settings can be customized using CSS as described above. To change the font, target the appropriate class within the generated HTML using CSS font-family, font-size, font-weight, etc. To change the color of the digits or other elements, similarly use CSS properties like color and background-color, targeting the right class names. Using your browser’s developer tools to inspect the HTML structure will be vital in determining which classes to style.

For example:

.flip-clock-digit .flip-clock-wrapper {
  font-family: 'Arial', sans-serif;
  font-size: 3em;
  color: #00FF00; /*Example - change to your desired color*/
}

Remember that this is a general example. The specific class names may vary depending on the FlipClock version and clock face used. Inspect the rendered HTML using your browser’s developer tools to identify the correct classes.

Clock Sizes

The size of the FlipClock is primarily controlled by the CSS applied to the container and its inner elements. You cannot directly set the size within the FlipClock constructor. You must adjust the size using CSS. This means adjusting properties like width, height, font-size, padding, and margin on the container element and its children. You can set specific dimensions, or use percentages or other relative units to control the clock’s size relative to its parent container. Again, inspecting the HTML using your browser’s developer tools will be essential to determine the appropriate classes to target for consistent sizing across different elements of the clock.

For example:

.clock { /* Assuming your clock is in a div with class 'clock' */
  width: 200px;
  height: 100px;
}
.flip-clock-digit {
  font-size: 50px;
}

Remember to adjust the selector (.clock in this example) to match the actual class or ID of your FlipClock container element. Experiment with different values and selectors to fine-tune the size and proportions as needed.

Advanced Features

Countdown Timers

FlipClock.js is easily adapted to create countdown timers. The core mechanism remains the same; you simply set the initial time value and use the clock.getTime() method to track the remaining time. When the clock reaches zero, you can handle the event using the stop event or by periodically checking the value returned by getTime().

For example, to create a countdown timer that starts at 60 seconds and stops at zero:

<div class="clock"></div>

<script>
  var clock = new FlipClock($('.clock'), 60, {
    countdown: true, // Important: enable countdown mode
    clockFace: 'MinuteCounter'
  });

  clock.on('stop', function() {
    alert('Time\'s up!');
  });
</script>

The countdown: true option is crucial here. Without it, the clock will count upwards from 60. The stop event is triggered when the counter reaches zero. Alternatively, you could check the time within the interval event:

clock.on('interval', function(time){
    if(time.getTime() === 0){
        alert("Time's up!");
    }
})

Remember to adjust the initial time value and clockFace according to your needs. You might also want to implement additional functionality to reset the timer or handle other user interactions.

Multiple Clocks

You can easily create multiple FlipClock instances on a single page. Each instance will be independent and will require its own container element and initialization call.

<div id="clock1"></div>
<div id="clock2"></div>

<script>
  var clock1 = new FlipClock($('#clock1'), 120, { clockFace: 'MinuteCounter' });
  var clock2 = new FlipClock($('#clock2'), 3600, { clockFace: 'HourlyCounter' });
</script>

This code creates two clocks: clock1 counts down from two minutes, and clock2 counts down from one hour. Ensure each clock has a unique container element (in this example, #clock1 and #clock2). Each clock will function independently. You can control and manage each clock instance separately using its respective methods and event handlers.

Integration with other libraries

FlipClock.js utilizes jQuery for DOM manipulation. It’s designed to work well within a larger jQuery-based application. Integration with other JavaScript libraries generally depends on their compatibility with jQuery.

If you’re using other libraries that don’t directly conflict with jQuery, you should be able to incorporate FlipClock.js without problems. However, be mindful of potential naming conflicts or library dependencies. Check for compatibility notes in the documentation of the other libraries you plan to use. If you are using a framework such as React, Angular or Vue.js, you will need to adapt the code according to the requirements of the framework. For example, you would typically wrap your FlipClock initialization within a lifecycle method of a component.

For example, if you use a library for handling user interactions, you might trigger FlipClock’s start() or stop() methods based on those interactions. Properly manage the order of loading of the scripts and ensure that any dependencies are met. You may need to adjust your project’s build process (if using a build tool like Webpack or Parcel) to ensure all necessary files are included and dependencies are handled correctly.

API Reference

FlipClock Constructor

The FlipClock constructor creates a new FlipClock instance.

Syntax:

new FlipClock(container, time, options);

Parameters:

Example:

var clock = new FlipClock($('#clock'), 60, { clockFace: 'MinuteCounter' });

Methods

FlipClock instances have several methods available to control their behavior:

Events

FlipClock instances trigger several events that you can listen for:

Example:

clock.on('interval', function(time) {
  console.log("Current time:", time.getTime());
});

clock.on('stop', function() {
  alert('Clock stopped!');
});

Remember to replace clock with your actual FlipClock instance.

Properties

FlipClock instances have several properties, though most of the direct manipulation of these should be done using the methods above. Directly accessing these properties is generally not recommended. Modifying them directly can lead to unexpected behavior.

It is important to note that the FlipClock.js API is relatively straightforward and mostly involves using the methods provided to control the clock’s behavior and listen for events rather than directly manipulating properties. The documentation may not comprehensively list every single internal property; modifying them directly may have unintended consequences and is not recommended.

Troubleshooting

Common Issues

Debugging Tips

Error Handling

FlipClock.js itself doesn’t have extensive built-in error handling mechanisms beyond the standard JavaScript error handling. If an error occurs during initialization or operation (such as an invalid selector), you’ll typically see a JavaScript error message in your browser’s developer console.

For more robust error handling within your application, you should wrap your FlipClock initialization and related code in try...catch blocks. This allows you to handle potential errors gracefully without crashing the entire application. For instance:

try {
  var clock = new FlipClock($('#clock'), 60, { clockFace: 'MinuteCounter' });
} catch (error) {
  console.error("Error creating FlipClock:", error);
  // Implement alternative behavior or display an error message to the user
}

You can add more specific error handling based on the types of errors you anticipate (e.g., checking for the existence of the container element before creating the FlipClock). Remember that error handling should be tailored to the specific needs of your application and the contexts in which errors might occur.

Contributing

We welcome contributions to FlipClock.js! Whether you find a bug, have a feature request, or want to improve the codebase, your help is appreciated.

Reporting Issues

If you encounter a bug or have a feature request, please follow these steps to report it effectively:

  1. Search for existing issues: Before creating a new issue, search the existing issues to see if someone has already reported the same problem or requested the same feature. This helps prevent duplicate reports.

  2. Create a clear and concise issue report: If you can’t find a similar issue, create a new one. Provide the following information:

  3. Provide a minimal reproducible example (if possible): If the issue involves code, create a small, self-contained example that demonstrates the problem. This makes it easier for others to reproduce and fix the issue.

Submitting Pull Requests

If you’d like to contribute code (bug fixes, new features, etc.), follow these steps:

  1. Fork the repository: Fork the FlipClock.js repository on GitHub to your own account.

  2. Create a new branch: Create a new branch from the main or develop branch (check the project’s guidelines for the preferred branch) for your changes. Give the branch a descriptive name related to your contribution.

  3. Make your changes: Make your changes to the codebase. Ensure your changes adhere to the coding style guide (see below).

  4. Test your changes: Thoroughly test your changes to ensure they work correctly and don’t introduce new bugs.

  5. Commit your changes: Commit your changes with clear and concise commit messages that explain what you’ve done. Follow conventional commit messages if possible (e.g., fix: resolve issue #123).

  6. Push your branch: Push your branch to your forked repository.

  7. Create a pull request: Create a pull request from your branch to the main or develop branch of the original FlipClock.js repository. Provide a clear description of your changes and why they are needed. Address any feedback you receive during the review process.

Coding Style Guide

The FlipClock.js project follows a consistent coding style to improve readability and maintainability. While the exact style might vary based on the project’s evolution, the general principles are:

Before submitting a pull request, make sure your code adheres to the project’s coding style. You might need to use a code formatter (like Prettier) to ensure consistency. Refer to the project’s contributing guidelines or any provided style guides for more specific details on their style preferences. If no specific style guide is provided, adhering to common JavaScript best practices is essential.