pixel-editor/js/Util.js

72 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-06-29 02:54:54 +03:00
// Acts as a public static class
class Util {
/** Tells if element is a child of an element with class className
*
* @param {*} element
* @param {*} className
*/
static isChildOfByClass(element, className) {
// Getting the element with class className
while (element != null && element.classList != null && !element.classList.contains(className)) {
element = element.parentElement;
}
// If that element exists and its class is the correct one
if (element != null && element.classList != null && element.classList.contains(className)) {
// Then element is a chld of an element with class className
return true;
}
return false;
}
/** Returns elementOrElementId if the argument is already an element, otherwise it finds
* the element by its ID (given by the argument) and returns it
*
* @param {*} elementOrElementId The element to return, or the ID of the element to return
* @returns The desired element
*/
2021-06-29 02:54:54 +03:00
static getElement(elementOrElementId) {
if (typeof(elementOrElementId) == "object") {
return elementOrElementId;
}
else if (typeof(elementOrElementId) == "string") {
return document.getElementById(elementOrElementId);
}
else {
console.log("Type not supported: " + typeof(elementOrElementId));
}
2021-06-29 02:54:54 +03:00
}
// Returns the text content of the element with ID elementId
2021-06-29 02:54:54 +03:00
static getText(elementId) {
return Util.getElement(elementId).textContent;
2021-06-29 02:54:54 +03:00
}
// Sets the text content of the element with ID elementId
2021-06-29 02:54:54 +03:00
static setText(elementId, text) {
Util.getElement(elementId).textContent = text;
2021-06-29 02:54:54 +03:00
}
// Gets the value of the element with ID elementId
2021-06-29 02:54:54 +03:00
static getValue(elementId) {
return Util.getElement(elementId).value;
2021-06-29 02:54:54 +03:00
}
// Sets the value of the element with ID elementId
2021-06-29 02:54:54 +03:00
static setValue(elementId, value) {
Util.getElement(elementId).value = value;
2021-06-29 02:54:54 +03:00
}
2021-06-29 02:54:54 +03:00
//add class .selected to specified element
static select(elementId) {
Util.getElement(elementId).classList.add('selected');
2021-06-29 02:54:54 +03:00
}
//remove .selected class from specified element
static deselect(elementId) {
Util.getElement(elementId).classList.remove('selected');
2021-06-29 02:54:54 +03:00
}
//toggle the status of the .selected class on the specified element
static toggle(elementId) {
Util.getElement(elementId).classList.toggle('selected');
2021-06-29 02:54:54 +03:00
}
}