Files
JavaScript.utils/src/utils/DomHelpers.mjs
Clemens Schwaighofer 5b69cecf9f
Some checks failed
JavaScriptUtilsVitest / ci-tests (push) Has been cancelled
Update isObject and isIterable, isArray
isObject only returns true for objects and nothing else.
Update cel/ael in the HTML builder to use isArray for array check
2025-11-27 17:29:03 +09:00

76 lines
1.7 KiB
JavaScript

/*
Description: DOM Helpers
Date: 2025/3/6
Creator: Clemens Schwaighofer
*/
export { loadEl, pop, expandTA, exists };
/**
* Gets html element or throws an error
* @param {string} el_id Element ID to get
* @returns {HTMLElement}
* @throws Error
*/
function loadEl(el_id)
{
let el = document.getElementById(el_id);
if (el === null) {
throw new Error('Cannot find: ' + el_id);
}
return el;
}
/**
* opens a popup window with winName and given features (string)
* @param {String} theURL the url
* @param {String} winName window name
* @param {Object} features popup features
*/
function pop(theURL, winName, features)
{
let __winName = window.open(theURL, winName, features);
if (__winName == null) {
return;
}
__winName.focus();
}
/**
* automatically resize a text area based on the amount of lines in it
* @param {string} ta_id element id
*/
function expandTA(ta_id)
{
let ta = this.loadEl(ta_id);
if (ta instanceof HTMLElement && ta.getAttribute('type') !== "textarea") {
throw new Error("Element is not a textarea: " + ta_id);
}
let maxChars = parseInt(ta.getAttribute('cols') ?? "0");
let ta_value = ta.getAttribute('value');
let theRows = [];
if (ta_value != null) {
theRows = ta_value.split('\n');
}
var numNewRows = 0;
for ( var i = 0; i < theRows.length; i++ ) {
if ((theRows[i].length+2) > maxChars) {
numNewRows += Math.ceil( (theRows[i].length+2) / maxChars ) ;
}
}
ta.setAttribute('row', (numNewRows + theRows.length).toString());
}
/**
* checks if a DOM element actually exists
* @param {String} id Element id to check for
* @return {Boolean} true if element exists, false on failure
*/
function exists(id)
{
return $('#' + id).length > 0 ? true : false;
}
// __END__