Visual data previews with vanilla JavaScript

Last modified: November 22nd, 2023

Live editing in CloudCannon is all based on an injected JavaScript object CloudCannon and custom events triggered on the document object.

CloudCannon Events#

When your website is loaded in the Visual Editor, CloudCannon will trigger CustomEvents on the global document object. This is a feature available in all major browsers.

Load Event#

Triggers when CloudCannon live editing API is available. Triggers before the CloudCannon object is injected onto the window object."

copied
document.addEventListener('cloudcannon:load', function (e) {
  onLiveEditorLoad(e.detail.CloudCannon);
});

Depending on when the JavaScript is run, the load event might have already been triggered. In this case, the CloudCannon object will be available on the global window object.

copied
if (!window.CloudCannon) {
  document.addEventListener('cloudcannon:load', function (e) {
    onLiveEditorLoad(e.detail.CloudCannon);
  });
} else {
  onLiveEditorLoad(window.CloudCannon);
}

Update event#

Using the CloudCannon object, we need to enable the other document events. To do this we need to use the following code:

Once this CloudCannon object is saved, you can enable live editing. To demonstrate, we are using the function called in the last code snippet.

copied
function onLiveEditorLoad(CloudCannon) {
  CloudCannon.enableEvents();
}

With that enabled, we can register an event listener to the update event. The cloudcannon:update event is triggered after every front matter change.

copied
document.addEventListener('cloudcannon:update', async function (e) {
  useNewPageProps(e.detail.CloudCannon);
});

All events provide the CloudCannon object available on the event details.

The CloudCannon Object#

All events provide the CloudCannon object available on the event details. Alternatively this object is available at window.CloudCannon. This object gives you access to the CloudCannon interface.

Fetching the current front matter value#

Using the CloudCannon object, we can fetch the latest value of the front matter. This paired with the update event is the key to live previews. To do this, we use the CloudCannon.value() function. This function returns a promise, when awaited will return a json object of the latest value.

copied
async function useNewPageProps(CloudCannon) {
  const latestValue = await CloudCannon.value();
}

Updating a front matter key#

Using the CloudCannon object, we can set a value of a key in the front matter. This allows us to build custom controls directly on our page. To do this, we use the CloudCannon.set(slug, value) function.

copied
CloudCannon.set('title', 'new title value');

Related Articles

Open in a new tab