Skip to main content Accessibility Feedback
Skip to Documentation Content

Web Components

Web components in Kelp provide a few different ways to customize and extend them without having to touch the underlying code.

Options & Settings

Every Web Component in Kelp exposes a set of options you can set using HTML attributes.

For example, the <kelp-toc> component lets you specify the heading level, a label for the list, a parent container to target, and any custom CSS to add to the generated list.

<kelp-toc
	level="h3"
	heading="On this page..."
	target="#content"
	list-class="list-unstyled"
></kelp-toc>

This is the same as passing an object of options into a class in a traditional JavaScript component.

// Kelp does NOT do this
// For illustration purposes only
const toc = new TableOfContents('#toc', {
	level: 'h3',
	heading: 'On this page...',
	target: '#content',
	listClass: 'list-unstyled'
});

Custom Events

Every web component in Kelp emits one or more custom events you can hook into to extend a component’s functions.

They follow the following naming convention: kelp-{component-name}:{event-type}.

For example, the <kelp-tabs> component emits a custom event when it first loads, and another whenever a new tab is selected.

You might, for example, load ajax content into a tab pane the first time it’s selected open.

document.addEventListener('kelp-tabs:select', async (event) => {
	if (event.detail.pane.hasAttribute('is-loaded')) return;
	const request = await fetch('/path/to/content');
	const response = await request.text();
	event.detail.pane.innerHTML = response;
	event.detail.pane.setAttribute('is-loaded');
});

Methods

Many web components in Kelp have methods you can run on the custom element.

For example, if the headings on your page updated, you can run the .render() method on a <kelp-toc> element to generate an updated table of contents.

<kelp-toc></kelp-toc>
const toc = document.querySelector('kelp-toc');
toc.render();

Properties

Some web components in Kelp include custom properties that surface information about the current state of the component.

For example, the <kelp-toggle-pw> element has an .isVisible property that returns true if the password is currently visible, and false if it’s masked.

<kelp-toggle-pw>
	<label for="password">Password</label>
	<input type="password" id="password">
	<button toggle>Toggle Password</button>
</kelp-toggle-pw>
const pw = document.querySelector('kelp-toggle-pw');
if (pw.isVisible) {
	console.log('The password is visible!');
} else {
	console.log('You cannot see it...');
}