Skip to main content Accessibility Feedback
Skip to Documentation Content

HTML Ajax

New! This component was just added to Kelp. Enjoy!

Dynamically update HTML in response to events.

Usage

Wrap the content you want to update in a <kelp-html-ajax> element with a unique ID.

Add an [events] attribute with the event names you want to listen for as a comma-separated list. You can optionally provide a [keys] attribute with a comma-separated list of event keys to filter by.

<kelp-html-ajax
	id="treasure-chest"
	events="kelp-form-ajax:success"
	keys="add-to-chest"
>
	<!-- Some dynamic or server-generated HTML -->
</kelp-html-ajax>

Options

Use custom attributes to configure component settings.

  • [events] - A comma-separated list of events to listen for (required).
  • [keys] - A comma-separated list of event keys to filter by.

Events

The <kelp-html-ajax> element emits a few events.

  • kelp-html-ajax:ready emits when the component is instantiated.
  • kelp-html-ajax:before-replace emits before fetching replacement HTML, and is cancellable with event.preventDefault().
  • kelp-html-ajax:replace emits after the HTML has been replaced.
  • kelp-html-ajax:remove emits if the element doesn’t exist in the new HTML and is about to be removed.
  • kelp-html-ajax:failed emits when new HTML cannot be fetched.

The event.detail object includes an .eventKeys object with the component’s ID as a value.

document.addEventListener('kelp-html-ajax:ready', (event) => {
	console.log('ready:', event.target);
});

document.addEventListener('kelp-html-ajax:before-replace', (event) => {
	console.log('The component is about to be replaced:', event.detail);
	// Prevent it from being replaced
	event.preventDefault();
});

document.addEventListener('kelp-html-ajax:replace', (event) => {
	console.log('The component was replaced.', event.detail);
});

document.addEventListener('kelp-html-ajax:remove', (event) => {
	console.log('The component was removed.', event.detail);
});

document.addEventListener('kelp-html-ajax:failed', (event) => {
	console.log('The component was NOT replaced.', event.detail);
});