YurbaJS

DOM

Helpers for inserting HTML and creating elements.

render
yjs.render(html, selector?, prepend?)
ParamTypeDefaultDescription
html required string HTML string to insert.
selector optional string | HTMLElement '#main' Target — a CSS selector string or an element reference.
prepend optional boolean false When true, inserts before existing children instead of after.
yjs.render('<li class="item">New</li>', '.list')

// Element reference + prepend
yjs.render('<li>First</li>', listEl, true)
create
yjs.create(tag, className?, innerHTML?, attrs?)  // → HTMLElement
ParamTypeDefaultDescription
tag required string HTML tag name.
className optional string '' Space-separated CSS classes.
innerHTML optional string '' Inner HTML content.
attrs optional object {} style and dataset values are assigned as objects; everything else is set directly as an element property.
// Basic
const btn = yjs.create('button', 'btn btn-primary', 'Save')

// With attrs
const input = yjs.create('input', '', '', {
    type: 'datetime-local',
    min: new Date().toISOString().slice(0, 16),
    style: { display: 'block', width: '100%' },
    dataset: { modal: 'photosModal' },
})

// Returns HTMLElement — chain freely
btn.addEventListener('click', () => { ... })
container.appendChild(btn)
on
yjs.on(el, events, fn)
ParamTypeDescription
el required HTMLElement Target element.
events required string Space-separated event names.
fn required function Event handler.
// Instead of ['dragenter', 'dragover', 'drop'].forEach(e => el.addEventListener(e, fn))
yjs.on(dropzone, 'dragenter dragover drop', e => {
    e.preventDefault()
    e.stopPropagation()
})

yjs.on(mediaWrapper, 'mouseup mouseleave', endScroll)

Network

Wrappers around the native fetch API. Neither method ever rejects — on HTTP error they return an error-shape object instead of throwing.

fetch
yjs.fetch(url, params?)  // → Promise<Response | ErrorObject>
ParamTypeDefaultDescription
url required string Request URL.
params optional object { method: 'GET' } Standard fetch init options.
On HTTP error returns { error: true, status, statusText, response, detail } instead of rejecting. Always check res.error before using the response.
const res = await yjs.fetch('/api/data')
if (res.error) return
const text = await res.text()
fetch_json
yjs.fetch_json(url, params?)  // → Promise<any | ErrorObject>
Same as fetch but auto-parses the response as JSON and sets Accept: application/json.
const data = await yjs.fetch_json('/api/posts')
if (data.error) return
data.items.forEach(item => { ... })
import
yjs.import(url)  // → Promise<void>
Dynamically loads a .js or .css file by appending it to <head>. Skips silently if already loaded. Detects type by file extension.
await yjs.import('/static/js/chart.js')
await yjs.import('/static/css/extra.css')
webContent
yjs.webContent(url)  // → Promise<HTMLElement>
Fetches HTML from a URL and returns the parsed <body> element.
const body = await yjs.webContent('/page.html')
const title = body.querySelector('h1')?.textContent

Async & Timing

Utilities for timing, debouncing, and async control flow.

sleep
yjs.sleep(ms)  // → Promise<void>
await yjs.sleep(1000)
console.log('1 second later')
debounce
yjs.debounce(fn, ms)  // → function
Returns a debounced version of fn — invocation is delayed until ms milliseconds have passed since the last call.
const search = yjs.debounce((value) => {
    fetchResults(value)
}, 300)

input.addEventListener('input', e => search(e.target.value))
task
yjs.task(seconds, fn)  // → timeoutId
Shorthand for setTimeout(fn, seconds * 1000). Returns the timeout ID for cancellation.
const id = yjs.task(5, () => console.log('5s later'))
clearTimeout(id)  // cancel
run
yjs.run(fn)
Calls fn() immediately. Convenience wrapper for IIFE-style inline execution.

URL

Helpers for parsing URLs and query strings.

getQuery
yjs.getQuery(param, search?)  // → string | null
ParamTypeDefaultDescription
param required string Query parameter name.
search optional string window.location.search Query string to parse. Defaults to the current page URL.
// URL: https://yurba.one/search?q=hello&page=2
yjs.getQuery('q')        // → 'hello'
yjs.getQuery('page')     // → '2'
yjs.getQuery('missing')  // → null
getPath
yjs.getPath(url?)  // → string
Strips query string and hash. Defaults to window.location.href.
yjs.getPath('https://yurba.one/user/sample?page=about#top')
// → 'https://yurba.one/user/sample'
getExtension
yjs.getExtension(url)  // → string
yjs.getExtension('https://cdn.yurba.one/photo.jpg?size=large')  // → 'jpg'
yjs.getExtension('/static/js/app.min.js')  // → 'js'

Clipboard & Media

copyToClipboard
yjs.copyToClipboard(text)  // → Promise<void>
btn.addEventListener('click', () => {
    yjs.copyToClipboard('https://yurba.one/user/sample')
        .then(() => new YurbaUI.Toast({ title: 'Copied!', iconType: 'success' }).show())
})
playsound
yjs.playsound(soundPath)  // → Audio
Creates an Audio instance, plays it, and returns it for further control.
const audio = yjs.playsound('/static/sounds/notify.mp3')
audio.volume = 0.5

Text & Format

String manipulation, pluralization and formatting utilities.

sprintf
yjs.sprintf(str, ...args)  // → string
Replaces each %s placeholder in str with the next argument.
yjs.sprintf('Hello, %s! You have %s messages.', 'Alex', 5)
// → 'Hello, Alex! You have 5 messages.'
num_word
yjs.num_word(value, words)  // → string
Returns the correct Slavic plural form. words is [singular, few, many] — e.g. for Russian/Ukrainian/Belarusian declension.
const forms = ['комментарий', 'комментария', 'комментариев']
yjs.num_word(1,  forms)  // → 'комментарий'
yjs.num_word(3,  forms)  // → 'комментария'
yjs.num_word(11, forms)  // → 'комментариев'
yjs.num_word(21, forms)  // → 'комментарий'
strgen
yjs.strgen(length?)  // → string
Generates a random alphanumeric string from [0-9a-zA-Z]. Default length: 10.
yjs.strgen()   // → 'aB3kR7mQzX'
yjs.strgen(6)  // → 'x4Kp1A'
formatBytes
yjs.formatBytes(bytes)  // → string
yjs.formatBytes(0)           // → '0 B'
yjs.formatBytes(1024)        // → '1.0 KB'
yjs.formatBytes(1_048_576)   // → '1.0 MB'
yjs.formatBytes(1_073_741_824)  // → '1.0 GB'
date
yjs.date(type?, params?)
typeReturnsparamsDescription
undefined Date new Date()
'unix' number Current timestamp in ms (Date.now()).
'timezone' string IANA timezone, e.g. 'Europe/Kyiv'.
'gmt' string GMT offset, e.g. '+0300'.
'short' string Locale date+time string.
'toDate' string { value: number } Unix timestamp → '15 Jun 2025 14:30:00'.
'custom' string { format?, date? } Format with tokens: dd mm yyyy h m s ms. Default: 'dd.mm.yyyy'.
yjs.date()                                    // → Date object
yjs.date('unix')                              // → 1718400000000
yjs.date('timezone')                          // → 'Europe/Kyiv'
yjs.date('toDate', { value: 1718400000 })     // → '15 Jun 2024 00:00:00'
yjs.date('custom', { format: 'dd.mm.yyyy h:m' })  // → '15.06.2025 14:30'

Data

Array and file utilities.

chunkArray
yjs.chunkArray(array, chunk)  // → array[]
Splits an array into sub-arrays of size chunk. The last chunk may be smaller.
yjs.chunkArray([1, 2, 3, 4, 5], 2)
// → [[1, 2], [3, 4], [5]]
fileBase64
yjs.fileBase64(file)  // → Promise<string>
Reads a File or Blob and resolves with its base64-encoded content (without the data:…;base64, prefix).
input.addEventListener('change', async () => {
    const b64 = await yjs.fileBase64(input.files[0])
    // send to API...
})

Device

mobileCheck
yjs.mobileCheck()  // → boolean
Returns true if the current device is a mobile or tablet, detected via user-agent string.
if (yjs.mobileCheck()) {
    // mobile-specific logic
}