Skip to content

Utils Functions

The Common JS component provides a comprehensive set of JavaScript utility functions for Metro UI applications. These utilities help with common tasks such as type checking, DOM manipulation, object handling, and more. Utilities functions are stored in the Metro.utils namespace.

// The utilities are available through the Metro.utils namespace
// Examples:
// Check if a value is a function and return function or false
const isFunction = Metro.utils.isFunc(myValue);
// Get element coordinates
const coords = Metro.utils.coords(element);
// Format seconds to time object
const time = Metro.utils.secondsToTime(3600); // {d: 0, h: 1, m: 0, s: 0}

The Common JS component provides the following utility methods:

MethodParametersReturnDescription
elementId(prefix)prefix: stringstringDeprecated use Hooks.useId(). Generates a unique element ID with the given prefix
$()NonejQuery or DomReturns jQuery if available, otherwise Dom
MethodParametersReturnDescription
isValue(val)val: anybooleanChecks if a value is defined, not null, and not empty string
isNull(val)val: anybooleanChecks if a value is undefined or null
isFunc(f)f: anybooleanChecks if a value is a function
isObject(o)o: anybooleanChecks if a value is an object
isObject2(o)o: anybooleanChecks if a value is an object but not an array
isTag(val)val: anybooleanChecks if a value is an HTML tag
isUrl(val)val: anybooleanChecks if a value is a URL
isVideoUrl(val)val: anybooleanChecks if a value is a video URL (YouTube, Vimeo, etc.)
isEmbedObject(val)val: anybooleanChecks if a value is an embed object (iframe, object, embed, video)
isDate(val, format, locale)val: any, format: string, locale: stringbooleanChecks if a value is a valid date
isDateObject(v)v: anybooleanChecks if a value is a JavaScript Date object
isInt(n)n: anybooleanChecks if a value is an integer
isFloat(n)n: anybooleanChecks if a value is a float
isType(o, t)o: any, t: stringbooleanChecks if a value is of a specific type
isNegative(val)val: numberbooleanChecks if a number is negative
isPositive(val)val: numberbooleanChecks if a number is positive
isZero(val)val: numberbooleanChecks if a number is zero
MethodParametersReturnDescription
isVisible(element)element: HTMLElementbooleanChecks if an element is visible
isMetroObject(el, type)el: HTMLElement, type: stringbooleanChecks if an element has a Metro component of the specified type
isJQuery(el)el: anybooleanChecks if a value is a jQuery object
isDom(el)el: anybooleanChecks if a value is a Dom object
isQ(el)el: anybooleanChecks if a value is a jQuery or Dom object
isOutsider(element)element: HTMLElementbooleanChecks if an element is outside the viewport
inViewport(el)el: HTMLElementbooleanChecks if an element is in the viewport
viewportOutByWidth(el)el: HTMLElementbooleanChecks if an element is outside the viewport by width
viewportOutByHeight(el)el: HTMLElementbooleanChecks if an element is outside the viewport by height
viewportOut(el)el: HTMLElementbooleanChecks if an element is outside the viewport by width or height
rect(el)el: HTMLElementDOMRectGets the bounding client rect of an element
coords(element)element: HTMLElementobjectGets the coordinates of an element relative to the document
hiddenElementSize(el, includeMargin)el: HTMLElement, includeMargin: booleanobjectGets the size of a hidden element
getStyle(element)element: HTMLElementCSSStyleDeclarationGets the computed style of an element
getStyleOne(el, property)el: HTMLElement, property: stringstringGets a specific CSS property value of an element
getInlineStyles(element)element: HTMLElementobjectGets all inline styles of an element
getCssVar(v)v: stringstringGets the value of a CSS variable
scrollTo(element, options)element: HTMLElement, options: objectNoneScrolls to an element smoothly
MethodParametersReturnDescription
getCursorPosition(el, e)el: HTMLElement, e: EventobjectGets the cursor position relative to an element
getCursorPositionX(el, e)el: HTMLElement, e: EventnumberGets the cursor X position relative to an element
getCursorPositionY(el, e)el: HTMLElement, e: EventnumberGets the cursor Y position relative to an element
positionXY(e, t, s)e: Event, t: string, s: stringobjectGets the position of an event (client, screen, or page)
clientXY(e, t)e: Event, t: stringobjectGets the client position of an event
screenXY(e, t)e: Event, t: stringobjectGets the screen position of an event
pageXY(e, t)e: Event, t: stringobjectGets the page position of an event
isRightMouse(e)e: EventbooleanChecks if the right mouse button was clicked
MethodParametersReturnDescription
secondsToTime(s)s: numberobjectConverts seconds to a time object with days, hours, minutes, and seconds
secondsToFormattedString(time)time: numberstringConverts seconds to a formatted time string (HH:MM:SS)
MethodParametersReturnDescription
func(f)f: stringFunctionCreates a new function from a string
exec(f, args, context)f: Function, args: array, context: objectanyExecutes a function with the given arguments and context
MethodParametersReturnDescription
objectLength(obj)obj: objectnumberGets the number of properties in an object
objectShift(obj)obj: objectobjectRemoves the property with the lowest key from an object
objectDelete(obj, key)obj: object, key: stringNoneDeletes a property from an object
objectClone(obj)obj: objectobjectCreates a shallow clone of an object
arrayDelete(arr, val)arr: array, val: anyNoneRemoves a value from an array
arrayDeleteByKey(arr, key)arr: array, key: numberNoneRemoves an item at a specific index from an array
arrayDeleteByMultipleKeys(arr, keys)arr: array, keys: arrayarrayRemoves items at multiple indexes from an array
nvl(data, other)data: any, other: anyanyReturns the first argument if it’s not null or undefined, otherwise returns the second argument
valueInObject(obj, value)obj: object, value: anybooleanChecks if a value exists in an object
keyInObject(obj, key)obj: object, key: stringbooleanChecks if a key exists in an object
inObject(obj, key, val)obj: object, key: string, val: anybooleanChecks if an object has a property with a specific value
MethodParametersReturnDescription
embedUrl(val)val: stringstringConverts a URL to an embedded HTML iframe
percent(total, part, round_value)total: number, part: number, round_value: booleannumberCalculates the percentage of a part relative to a total
between(val, bottom, top, equals)val: number, bottom: number, top: number, equals: booleanbooleanChecks if a value is between two numbers
parseMoney(val)val: stringnumberParses a money string to a number
parseCard(val)val: stringstringParses a card number string, removing non-numeric characters
parsePhone(val)val: stringstringParses a phone number string, removing non-numeric characters
parseNumber(val, thousand, decimal)val: string, thousand: string, decimal: stringstringParses a number string with custom thousand and decimal separators
nearest(val, precision, down)val: number, precision: number, down: booleannumberRounds a number to the nearest multiple of precision
bool(value)value: anybooleanConverts various values to boolean
decCount(v)v: numbernumberCounts the number of decimal places in a number
classNames(...args)args: any[]stringCombines class names into a space-separated string
join(...values)values: any[]stringJoins values with a separator (last argument is the separator)
copy2clipboard(v, cb)v: string, cb: FunctionNoneCopies a string to the clipboard and calls a callback
MethodParametersReturnDescription
newCssSheet(media)media: stringCSSStyleSheetCreates a new CSS stylesheet with optional media query
addCssRule(sheet, selector, rules, index)sheet: CSSStyleSheet, selector: string, rules: string, index: numberNoneAdds a CSS rule to a stylesheet
media(query)query: stringbooleanChecks if a media query matches
mediaModes()NonearrayGets the current media modes
mediaExist(media)media: stringbooleanChecks if a media mode exists
inMedia(media)media: stringbooleanChecks if a specific media mode is active
aspectRatioH(width, a)width: number, a: stringnumberCalculates height based on width and aspect ratio
aspectRatioW(height, a)height: number, a: stringnumberCalculates width based on height and aspect ratio
MethodParametersReturnDescription
encodeURI(str)str: stringstringEncodes a URI with special handling for brackets
updateURIParameter(uri, key, value)uri: string, key: string, value: stringstringUpdates or adds a parameter to a URI
getURIParameter(url, name)url: string, name: stringstringGets a parameter value from a URI
MethodParametersReturnDescription
github(repo, callback)repo: string, callback: FunctionNoneFetches GitHub repository information and calls a callback
pageHeight()NonenumberGets the height of the page
cleanPreCode(selector)selector: stringNoneCleans whitespace in pre code elements
getLocales()NonearrayGets available locales
addLocale(locale)locale: objectNoneAdds a new locale

The Common JS component doesn’t directly use CSS variables, as it’s a JavaScript utility library. However, some of its methods interact with CSS variables:

  • getCssVar(v) - Gets the value of a CSS variable
  • Many DOM-related utilities work with elements that may be styled using CSS variables
  1. Use type checking utilities (isFunc, isObject, etc.) to validate inputs before processing them
  2. Leverage DOM utilities for cross-browser compatible element manipulation
  3. Use the time formatting utilities for consistent time display across your application
  4. Prefer the built-in object and array utilities over custom implementations for better maintainability
  5. Use exec() for safely executing functions that might not exist or could throw errors

The Common JS utilities are designed to work in all modern browsers. Some utilities provide cross-browser compatibility for operations that might otherwise require browser-specific code.