Welcome to @kluntje/js-utils š
Kluntje/js-utils is a collection of really usefull js functions that can be imported in any project and speed up your daily javascript tasks.
Install
npm install @kuntje/js-utils
Usage
import { inViewport } from '@kluntje/js-utils/lib/dom-helpers';
const inView = inViewport(document.querySelector("#teaser"));
import { domHelpers } from "@kluntje/js-utils";
const inView = domHelpers.inViewport(document.querySelector("#teaser"));
Functions
api-helpers
- fetchJSON(url, [options]) ā
Promise.<T>
Calls API and returns JSON as Promise
array-helpers
- hasElement(array, element) ā
boolean
checks, if element is in given array
- isFilledArray(array) ā
boolean
checks, whether given Array exists and has at least one element
- mergeArraysBy(array1, array2, checker) ā
Array.<T>
merge two given arrays by the given checker function
- pushIfNew(array, newElement) ā
Array.<T>
pushes new Element to given array, if its not already in it
- removeItem(array, itemToRemove) ā
Array.<T>
removes specific Item from array and return new array
date-helpers
- addDays(date, daysToAdd, [zeroHours]) ā
Date
Adds given amount of days to given date
- addLeadingZero(inNumber) ā
string
Optionally Adds leading Zero to Numbers < 10
- isEqualDate(dateA, dateB) ā
boolean
Checks whether given dates are equal
- sanitizeDateGMTOffset(date) ā
string
Helper to make date parsing cross browser compatible
Some browsers (e.g. Safari) need the GMT offset part to be in format "+00:00"
This helper makes sure that any present GMT offset follows that format and can safely be parsed:
Date.parse("2020-01-01T12:13:14.000+0200") // throws error in Safari
Date.parse("2020-01-01T12:13:14.000+02:00") // succes
dom-helpers
- addClass(elements, ...classNames)
adds given classes to one or multiple elements
- find(parent, selector) ā
Element
| null
returns the first child of a specific parent matching the given selector
- findAll(parent, selector) ā
Array.<Element>
returns all children of a specific parent matching the given selector
- callback(node, index, nodeList)
- getCurrentMQ(mediaQueries) ā
string
returns current mediaQuery-name. e.g. "MQ2"
- getInnerText(el) ā
string
returns innerText of given Element
- getParent(element, parentSelector) ā
Element
| null
returns parent of specific class, if found
- getUniqueID() ā
string
returns a random String to be used as ID
- hasChild(parent, childSelector) ā
boolean
returns if a specific parent has a child matching the given selector
- hasClass(element, className) ā
boolean
returns if a specific element has given class
- inViewport(element, [parent]) ā
boolean
checks, whether an element is in the viewport
- isNodeList(target) ā
boolean
checks, if target is NodeList
- onEvent(target, events, handler, context, [options])
adds event with given parameters
- removeChildren(parent, selector)
removes all children of a specific parent matching the given selector
- removeClass(elements, ...classNames)
removes given class from element
- removeEvent(target, events, handler, context, [options])
removes event with given parameters
- toggleClass(elements, className, add)
toggles given class on given element
- waitFor(timeout) ā
Promise.<void>
resolves Promise after given timeout
- waitForAnimationEnd(el, [animationName]) ā
Promise
returns a promise which resolves after the animationend event
- waitForEvent(target, eventName, timeout) ā
Promise.<void>
waits for given event for a (optional) max-timeout
- waitForInitialization(component) ā
Promise.<void>
Promise that resolves, when the given component is initialized
- waitForTransitionEnd(el, [propertyName]) ā
Promise
returns a promise which resolves after the transitionend
event
function-helpers
- debounce(callback, [wait]) ā
function
returns a debounced function which when called multiple of times each time it waits the waiting duration
and if the method was not called during this time, the last call will be passed to the callback.
- decoratorGenerator(func) ā
function
generates a decorator factory for the provided helper function.
helper function should have this signature: (Function, ...args: any[]) => Function
- throttle(callback, [wait]) ā
function
returns a throttled function which when called, waits the given period of time before passing the last call during this time to the provided callback.
call .cancel()
on the returned function, to cancel the callback invocation.
object-helpers
getValue(obj, path) ā *
returns nested value without throwing an error if the parent doesn't exist
- isEqual(arg1, arg2) ā
boolean
compare two arguments, for object their toString values are compared
- isFilledObject(obj) ā
boolean
checks if provided argument is an object which has at least one entry in it.
- naiveClone(arg) ā
Nullable.<T>
| Array.<T>
returns a deep link of the provided argument
- toArray(arg) ā
Array.<T>
returns the argument wrapped in an array if it isn't array itself
- toString(arg) ā
string
returns stringified value for the given argument
string-helpers
- getCleanString(inputString) ā
string
removes all multi Whitespaces and Newlines in given string
- getWordCount(text) ā
number
returns number of words in a given text
- removeAllBS(inputString) ā
string
removes all Whitespaces in given string
- removeAllNL(inputString) ā
string
removes all Newlines in given string
- removeMultiBS(inputString) ā
string
removes multi Whitespaces in given string
- toCamelCase(str) ā
string
function to convert texts to camelCase for example ti generate attribute names
- toKebabCase(str) ā
string
converts the provided string to a kebab case (kebab-case)
url-helpers
- ensureHttpProtocol(url, useHttp) ā
string
Ensures that the given url has an http protocol. If the url does not have an http protocol, it will be prepended with https://. If the url already has an http protocol, it will be returned as is. If the protocol should be http instead of https, you can pass in the optional parameter useHttp
as true.
- removeHttpProtocol(url) ā
string
returns a string without the http or https protocol
Typedefs
dom-helpers
- callback :
function
iterates over all nodes in a node list
(necessary because IE11 doesn't support .forEach * for NodeLists)
fetchJSON(url, [options]) ā Promise.<T>
Calls API and returns JSON as Promise
Kind: global function
Param | Type |
---|
url | string |
[options] | RequestInit |
Example
const myApiResponse = await fetchJSON("https://some.api/path")
Example
fetchJSON("https://some.api/path").then((data) => console.log("myData:", data));
hasElement(array, element) ā boolean
checks, if element is in given array
Kind: global function
Param | Type |
---|
array | Array.<T> |
element | T |
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
if (hasElement(fruits, "Apple")) {
console.log("You got an Apple");
}
isFilledArray(array) ā boolean
checks, whether given Array exists and has at least one element
Kind: global function
Example
const myBooks = await fetchJSON("https://my-book-store.api/books");
if (isFilledArray(myBooks)) {
console.log(`${myBooks.length} Books found!`)
} else {
console.log("Sorry, no Books found");
}
mergeArraysBy(array1, array2, checker) ā Array.<T>
merge two given arrays by the given checker function
Kind: global function
Param | Type | Description |
---|
array1 | Array.<T> | |
array2 | Array.<T> | |
checker | function | if this function returns true for a specific element combination the elements are getting merged |
Example
const defaultUsers = [
{
name: "Admin",
mail: "admin@company.com"
},
{
name: "CI",
mail: "ci@company.com"
}
];
const projectUsers = [
{
name: "Admin",
mail: "admin@company.com"
},
{
name: "User1",
mail: "user-one@company.com"
},
{
name: "User2",
mail: "user-two@company.com"
}
];
const userList = mergeArraysBy(defaultUsers, projectUsers, (defaultUser, array) => {
return !array.some((projectUser) => projectUser.mail === defaultUser.mail)
})
pushIfNew(array, newElement) ā Array.<T>
pushes new Element to given array, if its not already in it
Kind: global function
Param | Type |
---|
array | Array.<T> |
newElement | T |
Example
const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruit = getInputValue(...)
const newFruitStore = pushIfNew(fruitStore, newFruit);
removeItem(array, itemToRemove) ā Array.<T>
removes specific Item from array and return new array
Kind: global function
Param | Type |
---|
array | Array.<T> |
itemToRemove | T |
Example
const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruitStore = removeItem(fruitStore, "Apple");
addDays(date, daysToAdd, [zeroHours]) ā Date
Adds given amount of days to given date
Kind: global function
Param | Type | Default | Description |
---|
date | Date | | |
daysToAdd | number | | |
[zeroHours] | boolean | false | set time to 0:00:00 |
Example
const today = new Date();
const tomorrow = addDays(today, 2);
addLeadingZero(inNumber) ā string
Optionally Adds leading Zero to Numbers < 10
Kind: global function
Example
const today = new Date();
const formattedDateSting = `${addLeadingZero(today.getDate())}.${addLeadingZero(today.getMonth() + 1)}.${today.getFullYear()}`;
isEqualDate(dateA, dateB) ā boolean
Checks whether given dates are equal
Kind: global function
Param | Type |
---|
dateA | Date |
dateB | Date |
Example
const dateA = new Date(2020, 1, 29, 22, 30);
const dateB = new Date(2020, 1, 29, 18, 20);
isEqualDate(dateA. dateB);
sanitizeDateGMTOffset(date) ā string
Helper to make date parsing cross browser compatible
Some browsers (e.g. Safari) need the GMT offset part to be in format "+00:00"
This helper makes sure that any present GMT offset follows that format and can safely be parsed:
Date.parse("2020-01-01T12:13:14.000+0200") // throws error in Safari
Date.parse("2020-01-01T12:13:14.000+02:00") // succes
Kind: global function
Returns: string
-
correctly formatted date
Param | Type | Description |
---|
date | string | date string to be sanitized for parsing |
Example
sanitizeDateGMTOffset("2020-01-01T12:13:14.000+0200")
addClass(elements, ...classNames)
adds given classes to one or multiple elements
Kind: global function
Param | Type |
---|
elements | Element | Iterable.<Element> | NodeListOf.<Element> | null |
...classNames | string |
Example
const button = document.querySelector('.button');
addClass(button, 'my-button');
Example
const inputs = document.querySelectorAll('input');
addClass(inputs, 'my-button');
find(parent, selector) ā Element
| null
returns the first child of a specific parent matching the given selector
Kind: global function
Param | Type |
---|
parent | Element | Document | null |
selector | string |
Example
const input = find(document, 'input');
findAll(parent, selector) ā Array.<Element>
returns all children of a specific parent matching the given selector
Kind: global function
Param | Type |
---|
parent | Element | Document | null |
selector | string |
Example
const inputs = findAll(document, 'input');
callback(node, index, nodeList)
Kind: global function
Param | Type |
---|
node | Node |
index | Number |
nodeList | NodeListOf.<T> |
getCurrentMQ(mediaQueries) ā string
returns current mediaQuery-name. e.g. "MQ2"
Kind: global function
Returns: string
-
Param | Type |
---|
mediaQueries | Array.<MQDefinition> |
Example
const myMqs = [
{
name: 'MQ2',
query: '(min-width: 769px)'
},
{
name: 'MQ1',
query: '(min-width: 0px)'
}
];
const curMQ = getCurrentMQ(myMqs);
getInnerText(el) ā string
returns innerText of given Element
Kind: global function
Example
const myArticle = document.querySelector('article');
const articleText = getInnerText(myArticle);
getParent(element, parentSelector) ā Element
| null
returns parent of specific class, if found
Kind: global function
Param | Type |
---|
element | Element |
parentSelector | string |
Example
const myText = document.querySelector('p');
const myArticle = getParent(myText, 'article');
getUniqueID() ā string
returns a random String to be used as ID
Kind: global function
hasChild(parent, childSelector) ā boolean
returns if a specific parent has a child matching the given selector
Kind: global function
Param | Type |
---|
parent | Element |
childSelector | string |
Example
const article = document.querySelector('article');
if (hasChild(article, '.cta')) console.log('please click');
hasClass(element, className) ā boolean
returns if a specific element has given class
Kind: global function
Param | Type |
---|
element | Element |
className | string |
Example
const cta = document.querySelector('button');
if (hasClass(cta, 'primary')) console.log("primary")
inViewport(element, [parent]) ā boolean
checks, whether an element is in the viewport
Kind: global function
Param | Type |
---|
element | Element |
[parent] | Element |
Example
const image = document.querySelector('image');
if (inViewport(image)) image.setAttribute('src', image.dataset('src'));
isNodeList(target) ā boolean
checks, if target is NodeList
Kind: global function
onEvent(target, events, handler, context, [options])
adds event with given parameters
Kind: global function
Param | Type |
---|
target | EventTarget | null |
events | string | Array.<string> |
handler | function |
context | Context |
[options] | AddEventListenerOptions |
Example
const buttons = findAll(document, 'button);
onEvent(buttons, 'click', () => console.log('button clicked'), this);
removeChildren(parent, selector)
removes all children of a specific parent matching the given selector
Kind: global function
Param | Type |
---|
parent | Element |
selector | string |
Example
const article = find('article);
removeChildren(article, '.ad');
removeClass(elements, ...classNames)
removes given class from element
Kind: global function
Param | Type |
---|
elements | Element | Iterable.<Element> | NodeListOf.<Element> | null |
...classNames | string |
Example
const button = document.querySelector('.button');
removeClass(button, 'active');
Example
const inputs = document.querySelectorAll('input');
removeClass(inputs, 'active');
removeEvent(target, events, handler, context, [options])
removes event with given parameters
Kind: global function
Param | Type |
---|
target | HTMLElement | Iterable.<HTMLElement> |
events | string | Array.<string> |
handler | function |
context | Context |
[options] | AddEventListenerOptions |
Example
const buttons = findAll(document, 'button);
removeEvent(buttons, 'click', () => console.log('button clicked'), this);
toggleClass(elements, className, add)
toggles given class on given element
Kind: global function
Param | Type |
---|
elements | Element | Iterable.<Element> | NodeListOf.<Element> | null |
className | string |
add | boolean |
Example
const button = find(document, 'button');
onEvent(button, 'click', () => toggleClass(button, 'active'), this);
waitFor(timeout) ā Promise.<void>
resolves Promise after given timeout
Kind: global function
Param | Type | Description |
---|
timeout | number | timeout in milliseconds |
Example
addClass(button, 'animate');
waitFor(300).then(() => removeClass(button, 'animate'));
Example
addClass(button, 'animate');
await waitFor(300);
removeClass(button, 'animate');
waitForAnimationEnd(el, [animationName]) ā Promise
returns a promise which resolves after the animationend event
Kind: global function
Param | Type | Description |
---|
el | HTMLElement | SVGElement | DOM Element which has the css animation |
[animationName] | string | keyframes' name. e.g. "slideOut" |
Example
el.classList.add("hide");
await waitForAnimationEnd(el, "fade-out");
el.parentElement.removeChild(el);
// css:
// .hide {
// animation: fade-out 0.5s forwards;
// }
waitForEvent(target, eventName, timeout) ā Promise.<void>
waits for given event for a (optional) max-timeout
Kind: global function
Param | Type | Description |
---|
target | EventTarget | |
eventName | string | |
timeout | number | timeout in milliseconds |
Example
addClass(button, 'animate');
waitForEvent(button, 'transitionend', 500).then(() => removeClass(button, 'animate'));
Example
addClass(button, 'animate');
await waitForEvent(button, 'transitionend', 500);
removeClass(button, 'animate');
waitForInitialization(component) ā Promise.<void>
Promise that resolves, when the given component is initialized
Kind: global function
Param | Type |
---|
component | Component |
Example
waitForInitialization(my-input).then(() => my-input.value = 'Hello World');
Example
await waitForInitialization(my-input);
my-input.value = 'Hello World';
waitForTransitionEnd(el, [propertyName]) ā Promise
returns a promise which resolves after the transitionend
event
Kind: global function
Param | Type | Description |
---|
el | HTMLElement | SVGElement | DOM Element which has the css transition |
[propertyName] | string | transition's propertyName. e.g. "width" |
Example
menu.classList.add("open");
await waitForTransitionEnd(menu, "transform");
input.classList.add("visible");
await waitForTransitionEnd(input, "opacity");
input.focus();
debounce(callback, [wait]) ā function
returns a debounced function which when called multiple of times each time it waits the waiting duration
and if the method was not called during this time, the last call will be passed to the callback.
Kind: global function
Debounce(100): scrollHandler(event) {
// ...
}
}
Param | Type | Default | Description |
---|
callback | function | | function to be called after the last wait period |
[wait] | number | 0 | waiting period in ms before the callback is invoked if during this time the debounced method was not called |
Example
const debounced = debounce(console.log, 500);
debonced("Hi");
debonced("Hello");
debonced("Hey");
if (neverMind) debonced.cancel();
Class Component {
constructor() {
window.addEventListener("resize", this.resizeHandler);
window.addEventListener("scroll", this.scrollHandler);
}
resizeHandler = debounce(event => {
}, 100);
decoratorGenerator(func) ā function
generates a decorator factory for the provided helper function.
helper function should have this signature: (Function, ...args: any[]) => Function
Kind: global function
Param | Type | Description |
---|
func | function | function to be wrapped with a decorator factory |
throttle(callback, [wait]) ā function
returns a throttled function which when called, waits the given period of time before passing the last call during this time to the provided callback.
call .cancel()
on the returned function, to cancel the callback invocation.
Kind: global function
Param | Type | Default | Description |
---|
callback | function | | function to be caled after the last wait period |
[wait] | number | 0 | waiting period in ms before the callback is invoked if during this time the debounced method was not called |
Example
window.addEventListener("resize", throttle(updateSlider, 100));
getValue(obj, path) ā *
Deprecated
returns nested value without throwing an error if the parent doesn't exist
Kind: global function
Returns: *
-
- returned the found value or undefined
Param | Type | Description |
---|
obj | Object | object to be looked for value |
path | string | a string with dot separated levels: e.g "a.b" |
Example
const obj = {
a: {
b: {
c: 1
},
d: true
}
};
getValue(obj, "a.b") === {c: 1};
getValue(obj, "a.f") === undefined;
isEqual(arg1, arg2) ā boolean
compare two arguments, for object their toString values are compared
Kind: global function
Example
if (!isEqual(oldState, newState)) console.log('state changed');
isFilledObject(obj) ā boolean
checks if provided argument is an object which has at least one entry in it.
Kind: global function
Example
isFilledObject({ k: "v" }) === true;
isFilledObject({}) === false;
isFilledObject("text") === false;
naiveClone(arg) ā Nullable.<T>
| Array.<T>
returns a deep link of the provided argument
Kind: global function
Param | Type |
---|
arg | Nullable.<T> | Array.<T> |
Example
const state = naiveClone(initialState);
toArray(arg) ā Array.<T>
returns the argument wrapped in an array if it isn't array itself
Kind: global function
Param | Type |
---|
arg | T | Array.<T> |
Example
const apple = "Apple";
const fruits = toArray(apple);
toString(arg) ā string
returns stringified value for the given argument
Kind: global function
Example
const submitData = toString(formData);
getCleanString(inputString) ā string
removes all multi Whitespaces and Newlines in given string
Kind: global function
Param | Type |
---|
inputString | string |
Example
const article = find(document, 'aricle');
const text = getCleanString(article.innerText);
getWordCount(text) ā number
returns number of words in a given text
Kind: global function
Example
const article = find(document, 'aricle');
const articleWords = getWordCount(article.innerText);
removeAllBS(inputString) ā string
removes all Whitespaces in given string
Kind: global function
Param | Type |
---|
inputString | string |
Example
removeAllBS('Hello My World ');
removeAllNL(inputString) ā string
removes all Newlines in given string
Kind: global function
Param | Type |
---|
inputString | string |
Example
const article = find(document, 'aricle');
const textString = removeAllNL(article.innerText);
removeMultiBS(inputString) ā string
removes multi Whitespaces in given string
Kind: global function
Param | Type |
---|
inputString | string |
Example
removeMultiBS('Hello My World');
toCamelCase(str) ā string
function to convert texts to camelCase for example ti generate attribute names
Kind: global function
Param | Type | Description |
---|
str | string | sequence of letters, dashes and spaces to be converted to camelCase |
Example
toCamelCase("some-text") === "someText";
toCamelCase("some other text") === "someOtherText";
toKebabCase(str) ā string
converts the provided string to a kebab case (kebab-case)
Kind: global function
Example
toKebabCase("keyValuePair") === "key-value-pair"
ensureHttpProtocol(url, useHttp) ā string
Ensures that the given url has an http protocol. If the url does not have an http protocol, it will be prepended with https://. If the url already has an http protocol, it will be returned as is. If the protocol should be http instead of https, you can pass in the optional parameter useHttp
as true.
Kind: global function
Param | Type | Default |
---|
url | string | |
useHttp | boolean | false |
Example
const url = 'https://www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
const url = 'www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
const url = 'http://www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
removeHttpProtocol(url) ā string
returns a string without the http or https protocol
Kind: global function
Example
const url = 'https://www.google.com';
const result = removeHttpProtocol(url);
console.log(result);
callback : function
iterates over all nodes in a node list
(necessary because IE11 doesn't support .forEach * for NodeLists)
Kind: global typedef
Param | Type | Default |
---|
nodeList | NodeListOf.<T> | |
[context] | any | window |
Example
const buttons = document.querySelectorAll('button');
forEachNode(buttons, (button, idx) => addClass(button, `my-button--${idx}`))
Author
š¤ Frederik Riewerts frederik.riewerts@gmail.com
Show your support
Give a āļø if this project helped you!
This README was generated with ā¤ļø by readme-md-generator