DOM element styles
Manipulate DOM styles with ease.
Crafting demo...
Result box:
import {resetElementStyles, updateElementStyles} from '@kaiverse/k/utils'import {useRef} from 'react'
export default function DOMStylesDemo() { const resultBoxRef = useRef<HTMLDivElement>(null)
return ( <> <form id="color-form"> <label className="fieldset w-full max-w-xs"> <span className="fieldset-label text-base">Change background color 🎨</span> <input className="input input-bordered w-full max-w-xs" name="inputColor" defaultValue="#000000" type="color" onChange={(e) => updateElementStyles(resultBoxRef.current, {'background-color': e.currentTarget.value}) } /> </label> </form>
<h3 className="mt-4">Result box:</h3> <div ref={resultBoxRef} className="h-32 bg-black rounded-sm"></div> <button className="btn btn-neutral mt-4" form="color-form" type="reset" onClick={() => resetElementStyles(resultBoxRef.current, ['background-color'])} > Reset </button> </> )}updateElementStyles
Section titled “updateElementStyles”Update styles of an element.
Type definition
Section titled “Type definition”function updateElementStyles( element: Element | HTMLElement | null, styles: CustomStyles, options?: UpdateStyleOptions,): void| Name | Type | Description |
|---|---|---|
CustomStyles | {[key: string]: string | number | undefined | null} | Styles to be updated. Key is CSS property name and should be a kebab-case string (eg: {'border-radius': '1rem'}). |
UpdateStyleOptions | {ignoreNilValue?: boolean; cache?: boolean | "once"} | updateElementStyles’s options |
Options
Section titled “Options”| Name | Type | Default | Description |
|---|---|---|---|
ignoreNilValue | boolean | false | If true, it will ignore updatiing the properties with undefined or null values. |
cache | boolean | "once" | false | Cache the original styles. Only cache value of provided properties that have been updated (depending on ignoreNilValue option).If set to "once", it won’t override existing cached styles. |
resetElementStyles
Section titled “resetElementStyles”Reset styles of an element.
Depending on provided properties, if the original styles have been cached, it will restore the original styles, otherwise, it will be removed from the current styles.
Type definition
Section titled “Type definition”function resetElementStyles(element: Element | HTMLElement | null, properties?: string[]): void