1.0.0-Beta • Published 1 year ago

dom-copilot v1.0.0-Beta

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

dom-copilot

A toolkit for dom

Usage

npm i dom-copilot

dom-copilot - v1.0.0-Beta

dom-copilot - v1.0.0-Beta

Table of contents

Functions

Functions

addClass

addClass(el, ...classes): void

Adds one or more classes to an element's class attribute, excluding classes that already exist, including SVG elements.

Example

const el = document.querySelector('.example-class')!;
addClass(el, 'new-class-1', 'new-class-2', 'example-class');

Since

1.0.0

Parameters

NameTypeDescription
elHTMLElement | SVGElementThe element to add class names to
...classesstring[]One or more classes to add to the element, passing one or multiple class names in each argument

Returns

void

Defined in

addClass.ts:15


addCss

addCss(selector, cssRules, title?): void

Add CSS rules to a stylesheet with a given title. If a stylesheet with that title does not exist, it will be created.

Example

addCss('.my-class', { color: 'red', backgroundColor: 'blue' }, 'my-stylesheet')

Since

1.0.0

Parameters

NameTypeDefault valueDescription
selectorstringundefinedThe CSS selector to which to apply the rules.
cssRulesStylePropsundefinedAn object containing CSS rules to apply.
titlestring'sheet'The title of the stylesheet.

Returns

void

Defined in

addCss.ts:23


addEvent

addEvent<T>(ele, type, eventHandle, options?): undefined | () => void

Adds an event listener to a given element.

Example

const button = document.querySelector('button');
addEvent(button, 'click', () => console.log('Button clicked!'));

Since

1.0.0

Type parameters

NameType
Textends HTMLElement | SVGElement

Parameters

NameTypeDescription
eleTThe element to which the event listener should be added.
typekeyof HTMLElementEventMapThe type of event to listen for.
eventHandle(ev: Event | ProgressEvent<EventTarget> | ClipboardEvent | UIEvent | AnimationEvent | MouseEvent | InputEvent | FocusEvent | CompositionEvent | DragEvent | ErrorEvent | FormDataEvent | PointerEvent | KeyboardEvent | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent) => voidThe function to be called when the event occurs.
optionsObjectAdditional options to modify the behavior of the event listener.
options.useCaptureundefined | booleanA boolean indicating whether events of this type should be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
options.useDebounceundefined | booleanA boolean indicating whether the event handler should be debounced.
options.useThrottleundefined | booleanA boolean indicating whether the event handler should be throttled.

Returns

undefined | () => void

A function to remove the event listener.

Defined in

addEvent.ts:19


canUseDom

canUseDom(): boolean

Returns a boolean indicating if the current environment is a browser environment.

Returns

boolean

Defined in

canUseDom.ts:4


cancelAnimationFrame

cancelAnimationFrame(handler): void

Cancel animation frame

Since

1.0.0

Example

let animation = requestAnimationFrame(changeHeight)
setTimeout(() => clearAnimationFrame(animation), 3000)

Todo

jest

Parameters

NameTypeDescription
handlernumberThe return that requestAnimationFrame back

Returns

void

Defined in

cancelAnimationFrame.ts:10


createDom

createDom<K>(domAttrs?): HTMLElementTagNameMapK

Creates a new DOM element based on the provided attributes.

Example

// Creating a new div with some text content and adding it to the document body
const myDiv = createDom({
  tagName: 'div',
  node: 'Hello, world!',
  container: document.body
});

Since

1.0.0

Type parameters

NameType
Kextends keyof HTMLElementTagNameMap

Parameters

NameTypeDescription
domAttrs?DomAttrs<K>Optional attributes for the new element.

Returns

HTMLElementTagNameMapK

The newly created element.

Defined in

createDom.ts:24


downloadByBlob

downloadByBlob(dataStream, fileName?): void

Downloads a file from a Blob object by creating a temporary object URL and clicking a link with a download attribute.

Example

// Download a file from an ExcelJS workbook
const workbook = new ExcelJS.Workbook();
// ...
const buffer = await workbook.xlsx.writeBuffer();
downloadByBlob(buffer, 'my-file');

Since

1.0.0

Parameters

NameTypeDefault valueDescription
dataStreamBlobPartundefinedThe data to download as a Blob object.
fileNamestring'unknown'The name to use for the downloaded file. Defaults to 'unknown'.

Returns

void

Defined in

downloadByBlob.ts:13


downloadByUrl

downloadByUrl(Url, type?): void

Downloads a file from a URL by creating a temporary object URL and clicking a link with a download attribute.

Example

downloadByUrl('https://example.com/my-file.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

Parameters

NameTypeDefault valueDescription
UrlstringundefinedThe URL of the file to download.
typestring'application/octet-stream'The MIME type of the file. Defaults to 'application/octet-stream'.

Returns

void

Defined in

downloadByUrl.ts:8


emptyDom

emptyDom(el): void

Removes all child nodes from the specified DOM element.

Example

// clear the contents of a div with id "my-div"
const el = document.getElementById('my-div')
emptyDom(el)

Parameters

NameTypeDescription
elHTMLElementThe DOM element to empty.

Returns

void

Defined in

emptyDom.ts:11


getBoundingClient

getBoundingClient(ele): ClientXY

Gets the client (x, y) coordinates of the specified element relative to the viewport.

Example

// get the bounding client of the element with id "my-ele"
const el = document.getElementById('my-ele')
const bounds = getBoundingClient(el)
console.log(bounds.x, bounds.y)

Parameters

NameTypeDescription
eleHTMLElementThe element to get the bounding client for.

Returns

ClientXY

The client (x, y) coordinates of the element.

Defined in

getBoundingClient.ts:18


getClass

getClass(el): string

Returns a string of all the CSS class names assigned to an element, including SVG elements.

Example

const el = document.querySelector('.example-class')!;
const classes = getClass(el);
console.log(classes); // 'example-class'

Since

1.0.0

Parameters

NameTypeDescription
elHTMLElement | SVGElementThe element to retrieve the class names from

Returns

string

A string containing class names

Defined in

getClass.ts:15


getCssVariable

getCssVariable(key, ele?): string

Gets the value of a CSS variable on the specified element or the root element.

Example

// Get the value of a CSS variable on the root element
const bgColor = getCssVariable('--main-bg-color');

// Get the value of a CSS variable on a specific element
const element = document.querySelector('.my-element');
const bgColor = getCssVariable('--main-bg-color', element);

Parameters

NameTypeDescription
keystringThe name of the CSS variable to get.
ele?HTMLElementThe element to get the CSS variable from. If not specified, defaults to the root element.

Returns

string

The value of the CSS variable.

Defined in

getCssVariable.ts:14


getOffsetPosition

getOffsetPosition(ele): Object

Gets the offset (left, top) position of the specified element relative to its parent element.

Example

// get the offset position of the element with id "my-ele" relative to its parent
const el = document.getElementById('my-ele')
const offset = getOffsetPosition(el)
console.log(offset.left, offset.top)

Parameters

NameTypeDescription
eleHTMLElementThe element to get the offset position for.

Returns

Object

The offset (left, top) position of the element relative to its parent.

NameType
leftnumber
topnumber

Defined in

getOffsetPosition.ts:13


getStyleProps

getStyleProps(element, propName?): string | StyleProps

Get the style properties of an element.

Example

Get all style properties of a specified element:

const element = document.getElementById('my-element');
const styleProps = getStyleProps(element);
console.log(styleProps);

Get the color property of a specified element:

const element = document.getElementById('my-element');
const color = getStyleProps(element, 'color');
console.log(color);

Since

1.0.0

Parameters

NameTypeDescription
elementHTMLElementThe element to get the style properties of.
propName?stringThe name of the property to get.

Returns

string | StyleProps

If propName is specified, returns the value of that property. Otherwise, returns an object containing all style properties and their values.

Defined in

getStyleProps.ts:38


getTextPixelWidth

getTextPixelWidth(text, options): number

Calculates the pixel width of the given text in the specified font.

Example

// Returns the pixel width of "Hello, World!" in the "20px Arial" font.
const width = getTextPixelWidth('Hello, World!', { fontFamily: 'Arial', fontSize: 20 })

Since

1.0.0

Parameters

NameTypeDescription
textstringThe text to calculate the width of.
optionsObjectOptions for the font.
options.font?stringThe font string to use, e.g. Arial.
options.fontFamily?stringThe name of the font family, e.g. sans-serif.
options.fontSize?string | numberThe size of the font in pixels.
options.fontWeight?string | numberThe weight of the font, e.g. bold.

Returns

number

The pixel width of the text in the specified font.

Defined in

getTextPixelWidth.ts:21


hasClass

hasClass(el, className): boolean

Checks if an element has a specified CSS class, including SVG elements.

Example

const el = document.querySelector('.example-class')!;
if (hasClass(el, 'example-class')) {
  console.log('Element has class "example-class".');
}

Since

1.0.0

Parameters

NameTypeDescription
elHTMLElement | SVGElementThe element to check
classNamestringThe CSS class to check for

Returns

boolean

If the element has the specified CSS class, returns true; otherwise, returns false.

Defined in

hasClass.ts:17


preload

preload(options): void

Parameters

NameType
optionsPreloadOptions

Returns

void

Defined in

preload.ts:23


rem

rem(designWidth, options?): void

Set font size of HTML tag according to the design width.

Example

// Sets the HTML font size based on a design width of 750 pixels
// with a maximum width of 2000 pixels and a minimum width of 375 pixels.
rem(750, { maxWith: 2000, minWith: 375 });

Parameters

NameTypeDescription
designWidthnumberThe design width of the page.
optionsRemOptionsThe optional parameters.

Returns

void

Defined in

rem.ts:17


removeClass

removeClass(el, className): void

Remove a class from an element.

Example

// Removes the class "active" from an element with the "target" ID.
const target = document.getElementById('target');
removeClass(target, 'active');

Parameters

NameTypeDescription
elHTMLElementThe target element.
classNamestringThe class name to remove.

Returns

void

Defined in

removeClass.ts:12


removeCssVariable

removeCssVariable(key, ele?): void

Removes a CSS variable from the specified element or the root element.

Example

// Remove a CSS variable from the root element
removeCssVariable('--main-bg-color');

// Remove a CSS variable from a specific element
const element = document.querySelector('.my-element');
removeCssVariable('--main-bg-color', element);

Parameters

NameTypeDescription
keystringThe name of the CSS variable to remove.
ele?HTMLElementThe element from which to remove the CSS variable. If not specified, defaults to the root element.

Returns

void

Defined in

removeCssVariable.ts:13


removeDom

removeDom(el): void

Remove a DOM element.

Example

removeDom(document.getElementById('my-element'));

Since

1.0.0

Parameters

NameTypeDescription
elElementThe element to remove.

Returns

void

Defined in

removeDom.ts:12


removeEvent

removeEvent(el, type, callback, options?): void

Remove an event listener from an element.

Example

const el = document.getElementById('my-element');
const callback = () => {
  console.log('Button clicked');
};

// Add the event listener
addEvent(el, 'click', callback, { useCapture: false });

// Remove the event listener
removeEvent(el, 'click', callback, { useCapture: false });

Since

1.0.0

Parameters

NameTypeDescription
elElementThe element to remove the event listener from.
typestringThe event type to remove.
callbackEventListenerThe callback function to remove.
optionsRemoveEventOptionsThe options object.

Returns

void

Defined in

removeEvent.ts:30


requestAnimationFrame

requestAnimationFrame(fn): number

The requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes as an argument a callback to be invoked before the repaint. The callback accepts a parameter, a timestamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire.

This method searches for the appropriate version of requestAnimationFrame() to use, with fallbacks for older versions in use by some browsers.

Example

const animate = () => {
  const element = document.getElementById('myElement')
  let position = 0
  const moveDown = () => {
    position += 2
    element.style.top = `${position}px`
    requestAnimationFrame(moveDown)
  }
  moveDown()
}
animate()

Since

1.0.0

Parameters

NameTypeDescription
fnFrameRequestCallbackA function specifying the animation to perform for each frame.

Returns

number

A numeric ID which can be passed to cancelAnimationFrame() to cancel the requested animation.

Defined in

requestAnimationFrame.ts:31


require

require(file, callback): void

Dynamically load a JavaScript file and execute a callback function.

Example

requireScript('path/to/script.js', () => {
  console.log('Script loaded');
});

Since

1.0.0

Parameters

NameTypeDescription
filestringThe URL of the JavaScript file to load.
callback(ev: Event) => anyThe callback function to execute when the script is loaded.

Returns

void

Defined in

require.ts:15


setClass

setClass(el, className): void

Sets the class attribute or className property of an element to the specified value.

Example

const myEl = document.getElementById('my-element')!;
setClass(myEl, 'my-class');
// The above call sets the class to "my-class" on #my-element.

Since

1.0.0

Parameters

NameTypeDescription
elHTMLElement | SVGElementThe element to set the class attribute/property for.
classNamestringThe class name(s) to set on the element.

Returns

void

Defined in

setClass.ts:13


setCssVariable

setCssVariable(key, val, ele?): void

Sets a CSS variable on the specified element or the root element.

Example

// Set a CSS variable on the root element
setCssVariable('--main-bg-color', '#ffffff');

// Set a CSS variable on a specific element
const element = document.querySelector('.my-element');
setCssVariable('--main-bg-color', '#ffffff', element);

Parameters

NameTypeDescription
keystringThe name of the CSS variable to set.
valstringThe value to set the CSS variable to.
ele?HTMLElementThe element to set the CSS variable on. If not specified, defaults to the root element.

Returns

void

Defined in

setCssVariable.ts:14


setOpacity

setOpacity(elem, opacity): void

Set the opacity of an element.

Example

const element = document.querySelector('.my-element');
setOpacity(element, 0.5);

Since

1.0.0

Parameters

NameTypeDescription
elemanyThe element whose opacity to set.
opacitynumberThe opacity value to set.

Returns

void

Defined in

setOpacity.ts:14


setStyleProps

setStyleProps<T>(element, props): void

Sets the style properties of an HTML element.

Example

const el = document.getElementById('myElement')
setStyleProps(el, { color: 'red', fontSize: '14px' })

Since

1.0.0

Type parameters

NameType
Textends HTMLElement

Parameters

NameTypeDescription
elementnull | TThe element to set style properties on.
propsPartial<{ [key: string]: string; }>The style properties to set, in the form of an object of key-value pairs.

Returns

void

void

Defined in

setStyleProps.ts:18


toBack

toBack(el): void

Moves the given element to the back of its parent's children.

Example

// Move the first div to the back of its parent container
const container = document.querySelector('.container');
const firstDiv = container.firstElementChild;
toBack(firstDiv);

Parameters

NameTypeDescription
elHTMLElementThe element to move to the back.

Returns

void

Defined in

toBack.ts:12


toFront

toFront(el): void

Moves the given element to the front of its parent's children.

Example

// Create a new element and add it to the DOM
const newDiv = document.createElement('div');
document.body.appendChild(newDiv);

// Move the new element to the front of the body
toFront(newDiv);

Parameters

NameTypeDescription
elHTMLElementThe element to move to the front.

Returns

void

Defined in

toFront.ts:14