Skip to content

Custom Elements

Brandon Jordan edited this page May 31, 2023 · 4 revisions

Basic elements

Elements are simply exported functions that pass a class instance that extends the jsUI Element class.

import {Element} from 'javascript-ui';

export function Custom() {
	return new CustomElement();
}

class CustomElement extends Element {
	constructor() {
		const element = document.createElement('tag');
		super(element);
		this.element = element;
	}
}

By extending Element, your element will inherit the standard methods that can be used on any HTMLElement. The CSS methods on every other Element will be added as well, as Element extends the Style class, but you can of course add your own methods to your class to add them for use with your element.

Multiple node element

If you need to create a group of elements for your element, use document fragment instead.

import {Element} from 'javascript-ui';

export function Custom() {
	return new CustomComponent();
}

class CustomComponent extends Element {
	constructor(name, options) {
		const element = new DocumentFragment();
		const tag = document.createElement('tag');
		element.append(tag);
                // and so on...
		super(element);
		this.element = element;
	}
}

The element property of your class is always expected to be an HTMLElement or DocumentFragment. Do not use DocumentFragment for only one element.

Accept child elements

To create an element that can contain other elements, simply accept an elements argument to your exported function, then pass it to the class instance you create to set it as an elements property. This will allow other elements to be nested inside your element.

import {Element} from 'javascript-ui';

export function Custom(elements) {
	return new CustomElement(elements);
}

class CustomElement extends Element {
	constructor(elements) {
		const element = document.createElement('tag');
		super(element);
		this.element = element;
                this.components = elements;
	}
}

Clone this wiki locally