Implementing a Countdown Timer in Phoenix LiveView

Implementation of FlipDown.JS and how Phoenix LiveView help us integrate it.
Recently, We implemented a countdown timer for one of our features in our app. We decided to use FlipDown JS because it is lightweight and easy to implement.
In some other time, I began researching on what other ways I could bring a countdown timer by using Elixir and Liveview only, but I think we can cover it up in another blog.
Implementation
Copy Flipdown JS file here and create a new file on your assets/vendor folder. If you do not have vendor folder, kindly create a new one.
Copy Flipdown CSS file here and create a new file on your assets/css folder. Make sure to import it on your main css file (for example: app.css)
Create a file named
count_down_timer.js. This will serve as our phoenix hook. See how Phoenix Hooks works here.
import Flipdown from '../../vendor/flipdown'
export const CountDown = {
mounted() {
let counter_id = this.el.id
let ends_at = parseInt(this.el.dataset.ends_at)
let counter = new Flipdown(ends_at, counter_id)
counter.start()
},
}
- Somewhere in your heex templates, create elements and apply the phoenix hooks.
<div class="m-0 h-full flex items-center justify-center">
<div
id="flipdown"
class="flipdown flipdown__theme-dark"
phx-hook="CountDown"
data-ends_at={@ends_at}
>
</div>
</div>
How will it work?
count_down_timer.jsis a phoenix hook that enables for Flipdown JS to communicate with our heex templateThe element that has
id=flipdownhas aclass=flipdown, this will inherit the styles inflipdown.cssand at the same time ourflipdown.jsFlipdown JS has light and dark them also. You can set it up by adding
flipdown__theme-darkorflipdown__theme-lightto your classes.data-ends_atis a data-attribute that we decided to pass throught in our phoenix hook. You can access it viathis.el.dataset.ends_at
Client Error Encounter
Uncaught TypeError: import_flipdown.default is not a constructor
If you encounter this kind of error message, possibly
This error means you are trying to use `import_flipdown.default` as a constructor (with `new import_flipdown.default(...)`), but the imported value is not a constructor function or class.
**Possible causes:**
- The module does not export a class/function as default.
- The import syntax is incorrect for the module format (CommonJS vs ESModule).
- You may need to use `import_flipdown.default()` (call as a function) or just `import_flipdown()`.
Thank you github copilot ^^^
If you will visit the code we copied, it is only declared as a simple class Flipdown function.
To fix this, go to flipdown.js and update it into
- class FlipDown {
+ export default class FlipDown {
// code continuation
}
Now you have a Count down Timer

Should you have any questions implementing this countdown timer, let me know in the comment section.
Happy coding.




