Package Exports
- base-elem-js
- base-elem-js/dist/js/base-elem-js.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (base-elem-js) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Base Elem Js
base-elem-js is a lightweight utility for DOM manipulation, including querying elements, adding/removing classes, setting attributes, and handling events. The minified package comes in at ~5kb! It is designed to work with a collection of elements or a single element.
Usage
To use the base-elem-js utility, you need to import it as follows:
import $be from 'base-elem-js;Use via a CDN
<script src="https://cdn.jsdelivr.net/npm/base-elem-js"></script>Base Elem Methods ($be().*)
find(selector: string, filter?: (elem: any, i: number) => boolean): BaseElemFinds elements matching the selector within the current elements and returns a new BaseElem instance.
findBy(type: FindBy, selector: string, filter?: (elem: any, i: number) => boolean): BaseElemFinds elements by type (id, class, or tag) within the current elements and returns a new BaseElem instance.
findOne(selector: string): BaseElemFinds the first element matching the selector within the current elements and returns a new BaseElem instance.
each(fn: (elem: HTMLElement, i: number) => void): BaseElemIterates over each element and applies the provided function.
css(attrs: Partial<CSSProperties> | string): BaseElem | stringSets or gets CSS properties for the current elements. If only passing a string, will return the property value.
addClass(cssNames: string | string[]): BaseElemAdds the specified class(es) to the current elements.
rmClass(cssNames: string | string[]): BaseElemRemoves the specified class(es) from the current elements.
tgClass(cssNames: string | string[], toggle?: boolean): BaseElemToggles the specified class(es) on the current elements.
hasClass(cssNames: string | string[], method: 'some' | 'every' = 'some'): booleanChecks if the current elements have the specified class(es).
attr(attrs: Record<string, string> | string): BaseElemSets or gets attributes for the current elements.
empty(): BaseElemEmpties the content of the current elements.
remove(): BaseElemRemoves the current elements from the DOM.
insert(html: string | HTMLElement | HTMLElement[], method: AppendMethod = 'append'): BaseElemInserts HTML or elements into the current elements using the specified method (append, prepend, after, before).
html(html: string): BaseElemSets the inner HTML of the current elements.
text(text: string): BaseElemSets the inner text of the current elements.
// types for the Event
type SyntheticEvent = `[${string}]`;
type NativeEvent = keyof HTMLElementEventMap;
type EventName = `${NativeEvent}.${string}` | NativeEvent | SyntheticEvent;
on(evtName: EventName | EventName[], fn: EventFn, delegateEl: string = null, config: boolean | AddEventListenerOptions = false): BaseElemAdds an event listener to the current elements. Namespace the events with a '.', for example click.myClickName. Pass in an array or single value for the evtName parameter. For a synthetic event pass it in [], so [syntheticEventName], this is essentially for the best Typescript support (otherwise string would invalidate the type checking of the event name).
// see EventName type right above
off(evtName: EventName | EventName[], config: boolean | AddEventListenerOptions = false): BaseElemRemoves an event listener from the current elements. Pass in the same string value as the 'on' method. Namespace with '.', or click.myClickName as the function name. Can also pass in an array of strings for the evtName param.
trigger(evtName: EventName, delgateEl?: string): BaseElemTriggers native events as well as synthetic events. Can also trigger namespaced events such as click.myClickName.
Examples
import $be from "base-elem-js";
const bes = $be.static;
$be('h1').css({color: 'green'});
const $hidden = $be('.hidden').css({display: 'block'}).attr({hidden: null});
console.log(bes.isHidden($hidden.elem[0]));
console.log('has "what" class',$be('ul').find('li').hasClass('what'));
const div = bes.make('div', {id: 'test', className: 'test'}, '<h2>Hello Make!</h2><p>Some copy goes here</p>');
const $div = $be(div);
$div.on('click.myClickName', (ev, elem) => {
console.log('clicked', elem.textContent);
},'h2');
$be(document.body).insert(div);
$div.insert('<p>Some more copy</p>', 'before');
$div.insert('<p>Copy Prepended</p>', 'prepend');Extending library
The BaseElem class can be refrenced for extension as seen below.
$be.BaseElem.prototype.foo = bar();Base Elem Static ($be.static)
make(tag: string, attrs?: Record<string, any>, html?: string): HTMLElementCreates a new HTML element with the specified tag, attributes, and inner HTML content.
isHidden(elem: HTMLElement): booleanChecks if the specified element is hidden (i.e., has display: none or visibility: hidden).
isVisible(elem: HTMLElement): booleanChecks if the specified element is visible (i.e., does not have display: none or visibility: hidden).
find(selector: string, base: HTMLElement = document): HTMLElement[]Finds elements matching the selector within the specified base element.
findBy(type: FindBy, selector: string, base: HTMLElement = document): HTMLElement[]Finds elements by type (id, class, or tag) within the specified base element.
findOne(selector: string, base: HTMLElement = document): HTMLElementFinds the first element matching the selector within the specified base element.
addClass(elem: HTMLElement, cssNames: string | string[]): voidAdds the specified class(es) to the element.
rmClass(elem: HTMLElement, cssNames: string | string[]): voidRemoves the specified class(es) from the element.
tgClass(elem: HTMLElement, cssNames: string | string[], toggle?: boolean): voidToggles the specified class(es) on the element.
hasClass(elem: HTMLElement, cssNames: string | string[], method: 'some' | 'every' = 'some'): booleanChecks if the element has the specified class(es).
attr(elem: HTMLElement, attrs: Record<string, string> | string): voidSets or gets attributes for the element.
empty(elem: HTMLElement): voidEmpties the content of the element.
remove(elem: HTMLElement): voidRemoves the element from the DOM.
insert(elem: HTMLElement, html: string | HTMLElement | HTMLElement[], method: AppendMethod = 'append'): voidInserts HTML or elements into the specified element using the specified method (append, prepend, after, before).
html(elem: HTMLElement, html: string): voidSets the inner HTML of the element.
text(elem: HTMLElement, text: string): voidSets the inner text of the element.
on(baseEl: EventElem, evtName: `${Event['type']}.${string}` | string, fn: EventFn, delegateEl: string = null, config: boolean | AddEventListenerOptions = false)Adds an event listener to the current elements. Namespace the events with a '.', for example click.myClickName.
off(evtName: string, config: boolean | AddEventListenerOptions = false);Removes an event listener from the current elements. Pass in the same string value as the 'on' method. Namespace with '.', or click.myClickName as the function name.
trigger( target: HTMLElement, evtName: string, delegateEl?: string, config?: boolean | AddEventListenerOptions);Trigger native, synthetic and namespaced navtive events.
Base Element Static Examples
import $bs from "base-elem-js";
const bes = $bs.static;
const div = bes.make('div', { id: 'test', className: 'test' }, '<h2>Hello Make!</h2><p>Some copy goes here</p>');
document.body.appendChild(div);
bes.addClass(div, 'new-class');
bes.rmClass(div, 'test');
bes.tgClass(div, 'toggle-class');
console.log(bes.hasClass(div, 'new-class'));
bes.attr(div, { 'data-test': 'value' });
console.log(bes.attr(div, 'data-test'));
bes.empty(div);
bes.html(div, '<p>New content</p>');
bes.text(div, 'New text');
bes.insert(div, '<p>Inserted content</p>', 'before');Animate/Transition Static Methods
This library includes a couple extra functions to help with transitions and simple animations.
useCssAnimate
The useCssAnimate function is a utility for handling CSS animations on HTML elements. It provides a way to start and end CSS animations with a specified duration and optional callback function.
const [cssAnimate, cssState] = useCssAnimate(elems: HTMLElement | HTMLElement[], baseCss: string = '');Adds the following CSS classes to and element or elements
[custom name]-startingorstarting(if second param is empty) at the start of the animation[custom name]-endingorendingas the animation is ending[custom name]-activeoractiveif the animation is active. Inactive state would be left without this class
Returns
[(start: boolean, duration?: number, endFn?: () => void) => void, CSSActionStates]: A tuple containing: A function to start the animation. An object representing the CSS action states.
Example
const [cssAnimate, cssState] = useCssAnimate(element, 'my-animation');
// To start the animation
cssAnimate(true, 500, () => {
console.log('Animation started');
});
// To end the animation
cssAnimate(false, 500, () => {
console.log('Animation ended');
});
console.log(cssState.starting) // returns the name of the starting class
console.log(cssState.ending) // returns the name of the ending class
console.log(cssState.active) // returns the name of the active classuseTransition
The useTransition function is a utility for managing transitions. It provides a way to handle the start and end of transitions with a specified duration.
Returns
Function: A function that takes three parameters:
startFn ((...args: any) => void): A function to be called when the transition starts.
endFn ((...args: any) => void): A function to be called when the transition ends.
duration (number, optional): The duration of the transition in milliseconds. Default is 300ms.
const transition = useTransition();
const startTransition = () => {
console.log('Transition started');
};
const endTransition = () => {
console.log('Transition ended');
};
// Start the transition with a duration of 400ms
transition(startTransition, endTransition, 400);Internal Functionality
The useTransition function maintains the state of the transition using a boolean flag (inTransition) and a timeout (tto). It also keeps track of the current end transition function (currEndTransitionFn).
When the returned function is called:
- If a transition is already in progress, it clears the current timeout and calls the current end transition function.
- It then calls the provided startFn to start the transition.
- It sets a timeout to call the provided endFn after the specified duration, marking the transition as complete.
This ensures that transitions are properly managed and do not overlap.