Wix Blocks Tutorial: Creating a Countdown Widget

20 min read
Wix Blocks is open to all Wix Studio users. To get access to Blocks, join Wix Studio.
This tutorial shows you how to build a countdown widget, which counts down to a specific date. It also contains a registration widget where site visitors can register and receive an email notification the day before your event. You will also learn how to install your countdown widget on a site and explore all the key features of Blocks.
countdown widget

What you get in the template

To make things easier, we've created a template so that you can get started right away.

The template contains:
  • A countdown widget. You need to complete its design and code its functions and properties.
  • A registration widget which you need to complete and add to your countdown widget.
  • Some public utilities that you can use to implement your widget's functionality.
  • Some backend code that you can use to implement the functions of your email notification.

Get the template

Step 1 | Complete the Design of Your Widget

To build this widget, start with this template and edit it under your Wix account. The template has been left incomplete so that you can learn how to add elements to your widget.
The widget is designed with a grid so that you can easily align and place elements.

  1. Open the template. 
  2. Click Countdown under Widgets and Design
  3. Click Add Elements Add icon in the top bar.
  4. Select Text. Drag and drop a 48px Title box into your widget.
  5. Click Edit Text and change the text to SS.
  6. Change the text color to white and center the text using the Inspector
  7. Select the text box and move it into the grid square above the SECONDS label using move elements icon.
  8. Resize it using stretch icon.

Learn more about designing your widget


Step 2 | Add and Define Your Widget's API Properties

You can define an API for your widget, so that the site creator who installs the widget can interact with it through code. The API can contain properties, events and exported functions.

This widget uses two properties:
  • endDate: Defines the end date when the countdown reaches zero. Using this property, site creators can change the end date so that the widget is customized for their site.
  • emailId: Determines the email message that will be sent to users when they sign up for a notification.

Learn more about widget API properties

Give your widget elements an ID

First you need to give your widget's elements an ID so that you can easily refer to them in the code.
  1. Click on the text box.
  2. Give the text box an ID in the Properties & Events properties icon panel. In this example the ID is secondsTxt. Note that the other elements have already been give IDs.

Define the "endDate" and "emailId" properties

  1. Click Add New Property in the API properties icon panel.
  2. Enter the property name, endDate.
  3. Select the property type, in this case, Date and Time (the date is displayed in US format mm/dd/yyyy).
  4. Select a default value (the site creator will be able to change this when they install your widget in the editors).
  5. Hover over Properties and click the add icon icon that appears.
  6. Create another property for the triggered email and call it emailId. This is a Text type property with no default value.

Step 3 | Add Code to Make Your Widget Work


To make your widget count down we need to create a function in the code that calculates the remaining time until the end date. To do this, your template comes with some pre-installed utilities that you can find in the Public & Backend public and backend icon menu. 

Blocks uses a new global variable, $widget and the property, $widget.props, that holds all the properties that you have defined for your widget.

Blocks also uses Velo autocomplete, so that you can write code more easily.

Learn more about the widget API

Import your utilities

  1. Click on the Public & Backend menu.
  2. Select dateUtils.js under Public. This opens the file in the code panel.

Change the code to consider your new function

Create a function, updateTime(), so that your countdown widget will update the count. Your new function should look like this:

1$widget.onPropsChanged(function () {
2});
3    function updateTime() {
4    const {days, hours, minutes, seconds} = getRemainingTime (new Date($widget.props.endDate));
5    $w('#daysTxt').text = days.toString();
6    $w('#hoursTxt').text = hours.toString();
7    $w('#minutesTxt').text = minutes.toString();
8    $w('#secondsTxt').text = seconds.toString();
9 }

You also need to set an interval for how often the widget updates the remaining time.
To do this, add the following code in your onReady() function. This updates the widget every second.

1$w.onReady(function () {
2    updateTime();
3    if (wixWindow.viewMode !== "Editor") {
4        setInterval(updateTime, 1000);
5    }
6});
Edit time condition
Velo code only runs when you click preview or when you open the live site. The Blocks onReady code runs also during editing time, so that you can see it in action while working in the editor. We use the above condition so that your countdown widget doesn't count down during editing time. 

Preview your widget and test its API properties

You are ready to preview your widget and its API properties.

  1. Click Preview. Your widget should countdown every second to the end date.
  2. Click Test API Properties. A panel appears with the default value you set earlier. 
  3. Change the date to check if the widget responds and counts down to the new date.

Step 4 | Create and Code a Custom Panel

You can create a custom settings panel so that site creators can change the settings of your widget when they install it on a site. In this example the custom settings panel allows the site creator to change the end date and define an email ID that determines which email will be sent to users when they register to receive notifications.

Learn more about panels

Create a custom panel

  1. Click on the Panels tab in the top bar.
  2. Click Create Panel.
  3. Name your panel. In this example, "My settings".
  4. Click Create Panel.
  5. Click + Add Element.
  6. Select Text Input. This will be for the end date.
  7. Click Properties & Events propeties icon . Give your text input an ID - endDateInput.
  8. Select the text element and click Settings.
  9. Add the name "End Date" in the Field Title field.
  10. Delete the text in the Default Text field.
  11. Set the placeholder text to "End Date".
  12. Add a section divider.
  13. Click Settings. Add a title in the Section Title field. In this example, "Triggered email".
  14. Add another Text Input. Give your text input an ID - emailIdInput.
  15. Select the text element and click Settings.
  16. Add the name "Email ID" in the Field Title field.
  17. Delete the text in the Default Text field.
  18. Set the placeholder text to "Email ID".
The design of your custom panel is complete. Now you need to implement it by adding code.

Add code to your custom panel


You want your custom panel to display the current end date and email ID when it loads. The site creator uses the panel to change these values. You need to add code to the panel so that when these inputs change, it updates your widget.

To enable panel elements to interact with your widget and perform actions in the editor, you can use the Velo wix-widget module in your code.

To use the Widget API, import wixWidget from the wix-widget module.

Insert the following code before your onReady() function.

1import wixWidget from 'wix-widget';

You want your widget to update when the values change so you need to register an onChange event. You also need to add async in your onReady () function as you will be using some asynchronous functions.

Your onReady() function should look like this:

1$w.onReady(async function () {
2    const { endDate, emailId } = await wixWidget.getProps();
3    $w('#endDateInput').value = endDate;
4    $w('#emailIdInput').value = emailId;
5
6    $w('#endDateInput').onChange(e => {
7        wixWidget.setProps({ endDate: e.target.value });
8    });
9
10    $w('#emailIdInput').onChange(e => {
11        wixWidget.setProps({ emailId: e.target.value });
12    });
13});
Click run icon Run or Preview to check your code

Step 5 | Configure Your Widget

Now that your panel is designed and coded you need to configure your widget so that your panel connects to one of your widget's action bar buttons.

The Configurations tab enables you to control how your widget behaves when a site creator installs and customizes it on a site. You can give your widget and its elements display names, so that it is clear to site creators what your widget does. You can also make changes to the floating action bars that appear in the editors when site creators select elements in your widget.

Learn more about configuration

Add your custom panel to your widget's floating action bar

  1. Click Configuration in the top bar. 
  2. Select your countdown widget. A floating action bar appears.
  3. Click Settings.
  4. Click settings icon Action Button Settings. The Main Action Settings panel appears.
  5. Select My settings from the dropdown list to select your custom panel.

Step 6 | Add a Second (Inner) Widget and Implement the Registration Logic

The template comes with a second widget called Registration. You can find it under Widgets and Design

When you click Layers you can see that it has been created as a multi-state box with three states. It has a button labelled Register, which changes to Submit when the site visitor clicks. It also has a field box where site visitors can add their email address. A thank-you message appears when a site visitor has registered.

This widget also comes with a design preset which can be used for mobile view.

Learn more about design presets

Add your registration widget to the countdown widget

You're now ready to add your registration widget to your first widget, the countdown widget. In Blocks, you can create lots of different widgets and add them to other widgets. 

Learn more about working with widgets within widgets
  1. Working in the Design tab, select your countdown widget.
  2. Click More Options more options and select Add Widget.
  3. Select Registration. Your inner widget appears in the middle of your countdown widget.
  4. Drag and stretch your innner widget to fit the lower section of your countdown widget.
  5. Change its ID to registration in Properties & Events propeties icon.
Another way to add a widget
You can also add an inner widget by clicking the  add button Add Elements menu. Select MY WIDGETS and drag and drop the widget you want to add into the first widget.

Implement the registration logic in the main widget's code

You'll implement the code for user registeratiion in the main (countdown) widget, using the pre-installed utility, contactUtils.js. It uses the wix-crm API to connect your contact to your collection.

This code directs the information to your collection. It uses the utility you will use later when you create a collection. You can see getSubscriptionsCollectionName() in the code.

  1. Create a new async function.
  2. Call it onSubmit. It uses the create contact utility.

Your code should look like this:

1 async function onSubmit({ email }) {
2   const contact = await createContact(email);
3   wixData.insert(getSubscriptionsCollectionName(), {
4       endDate: new Date($widget.props.endDate),
5       emailId: $widget.props.emailId,
6       contactId: contact.contactId
7   });
8 }
9

Register for the onSubmit event

In your onReady(), after your updateTime() function, add the following code:

1$w('#registration').onSubmit(onSubmit);
Backend code is already included
The backend code is already implemented in your template in Blocks. It includes an export function, notify(), which uses the pre-installed utilities. It checks the remaining time, triggers the email when ready and updates the collection. You need to invoke this in the editor, as explained below in Step 10.

Step 7 | Build Your App and Give it a Namespace

Now you are ready to build your app for the first time. Your first build will be a major build. Later, when you are working on your app you can choose to do a minor build or a major build. A minor version is updated automatically on all the sites where it appears. You just need to refresh the page. When you do a major build a site creator needs to update your app manually. A dot appears next to the name of the app Installed Apps panel in the Editor so that site creators know there is a new version available. 

Learn more about versions in Blocks

When you click build for the first time blocks prompts you to give your app a namespace. This namespace is used to refer to your collection in Velo code in the editors and in the app’s code in Blocks.

Learn more about the app namespace

Your first build

  1. Click Build.
  2. Enter a namespace for your app and click Next.
  3. Select Major Version and click Build.
  4. You get a message that Version 1.0 is built. Click Got it to continue working on your app.

Step 8 | Add a Collection to Your Widget

Now you need to create a collection to store all of the subscriptions. Collections in Blocks are empty placeholders that you design in Blocks, which will be filled with data once the app is installed on a site. Learn more about collections in Blocks

The template has a pre-installed utility called getSubscriptionsCollectionName(), in collectionUtils.js under Public & Backend. It constructs the full name of the collection so that you don't have to add your full app namespace every time you refer to it in the code.

Configure your collection utility

  1. Click collectionUtils.js under Public & Backend.
  2. Add your app's namespace.
Your code should look like this, with your own namespace.
1
2const NAMESPACE = '@mywixaccount/my-app-namespace';
3
4export function getSubscriptionsCollectionName() {
5    return `${NAMESPACE}/subscriptions`;
6}

Create your collection

  1. Click Databases
  2. Click + Create collection
  3. Give your collection a meaningful name. In this example, Subscriptions.
  4. Click Create

Add fields to your collection

  1. Click add button to add a field to your collection.
  2. Select Date from the Field Type drop down menu.
  3. Enter endDate in the Field Name field. This will be the last date up until which people can register.
  4. Click Save.
  5. Now add a Text type field and call it emailId for the triggered email.
  6. Add another Text type field and call it contactId. This will store the contact details of registered users.
  7. Now create a Boolean type field and call it notified. This ensures that subscribers will be notified only once.

Set permissions for your collection

You want any site visitor to be able to add content to your collection by subscribing. 

  1. Click More Options more options icon for your collection from the Databases menu.
  2. Select Permissions & Privacy
  3. Select the dropdown menu Can add content.
  4. Select Anyone.
  5. Click Save.

Step 9 | Install Your App on a Site in the Wix Editor

You can install your widget on any of the editors. The following example uses the Wix Editor. Before you install your app you need to build your app a second time. This will be a major build because you have created a collection.
  1. After building your app, open your website.
  2. Click Add apps add apps icon
  3. Click Custom Apps. A list of all your apps appears.
  4. Select your app from the Available apps list.
  5. Click Install App.
  6. Click Add Elements add elements icon.
  7. Select My Widgets.
  8. Double click your widget to add it to your site. 

You widget is fluid and you can select its elements so that you can customize the widget to your site. You can also open the settings panel and change the default end date. 

Set an Email ID

Users can register for an email notification. You need to create the email that will be sent and to get an ID for it so that the widget API can identify which email needs to be sent.
  1. Open My Dashboard from the Site menu in the top bar.
  2. Go to Triggered Emails in Developer Tools.
  3. Click Get Started
  4. Enter a subject.
  5. Design the email using the editor tools.
  6. Click Save & Publish.
  7. Add the sender details, the From name and the Reply-to email and click Save.
  8. Click Got it.
  9. Click Save & Publish again. You get a generated identification code that links to the email that you have designed so that it will be sent to anyone who registers. 
  10. Enter this code in your custom panel in the Email ID field.

Use Backend Code in Wix Editor to Notify Subscribers

Backend code is included with your app in Blocks, but you need to invoke the notification in the editor.

Invoke your notify function

  1. Click + New web module under Backend in Public & Backend in the Wix editor.
  2. Call it backend.jsw.
  3. Import the backend function in your site's code section under backend.jsw.

Your code should look like this:

1import { notify } 'myWixId/my-application-name-backend';

Now create an export function invokeNotify in backend.jsw in your site's code section.

Your code should look like this:

1export function invokeNotify() {
2     return notify ();
3}
Now you need to create a scheduled job. 

  1. Click Add add icon in Backend
  2. Click settings icon Add scheduled jobs. Add the following code under jobs.config in your site's code section. In this example the notify function is invoked at 10 minutes past the hour, every hour.

Your code should look like this:
1{
2   "jobs": [{
3       "functionLocation": "/backend.jsw",
4       "functionName": "invokeNotify",
5       "description": "",
6       "executionConfig": {
7           "cronExpression": "10 * * * *"
8       }
9   }]
10}

Step 10 | Test Your App

Now you are ready to test your app. 

  1. Publish your site. 
  2. Register to receive an email notification. 
  3. Go back to the editor and check your collection. 
  4. You can see there is a new subscriber. When the notification email is sent you will also see a tick in the notified field.
Check your triggered emails
You can also check in Triggered Emails under Developer Tools in your dashboard to see if the email has been sent.

Did this help?

|