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"));
// You can also import from top level. But this is not suitable for three shaking!
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-01T1214.000+0200") // throws error in Safari Date.parse("2020-01-01T1214.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
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
*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.
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
// use with async/await
const myApiResponse = await fetchJSON("https://some.api/path")
Example
// use as normal promise
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
| Param | Type |
|---|---|
| array | Array.<T> |
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)
})
// userList
// [
// {
// "name": "CI",
// "mail": "ci@company.com"
// },
// {
// "name": "Admin",
// "mail": "admin@company.com"
// },
// {
// "name": "User1",
// "mail": "user-one@company.com"
// },
// {
// "name": "User2",
// "mail": "user-two@company.com"
// }
// ]
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"); // ["Banana", "Orange", "Mango"]
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 000 |
Example
const today = new Date();
const tomorrow = addDays(today, 2);
addLeadingZero(inNumber) ⇒ string
Optionally Adds leading Zero to Numbers < 10
Kind: global function
| Param | Type |
|---|---|
| inNumber | number |
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); // true
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-01T1214.000+0200") // throws error in Safari Date.parse("2020-01-01T1214.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") // "2020-01-01T12:13:14.000+02:00"
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 -
- mediaQuery name e.g. MQ1
| 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
| Param | Type |
|---|---|
| el | HTMLElement |
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
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
| Param | Type |
|---|---|
| target | any |
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();
// logs only "Hey", and when `neverMind === false`, doesn't log anything.
// or instead of decorator on class methods
Class Component {
constructor() {
window.addEventListener("resize", this.resizeHandler);
window.addEventListener("scroll", this.scrollHandler);
}
resizeHandler = debounce(event => {
// event handlers logic
}, 100);
// or when the decorator is imported:
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
| Param | Type |
|---|---|
| arg1 | T |
| arg2 | T |
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
| Param | Type |
|---|---|
| obj | any |
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); // ["Apple"]
toString(arg) ⇒ string
returns stringified value for the given argument
Kind: global function
| Param | Type |
|---|---|
| arg | * |
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
| Param | Type |
|---|---|
| text | string |
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 '); // HelloMyWorld
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'); // 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
| Param | Type |
|---|---|
| str | string |
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);
// => 'https://www.google.com'
const url = 'www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
// => 'https://www.google.com'
const url = 'http://www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
// => 'http://www.google.com'
removeHttpProtocol(url) ⇒ string
returns a string without the http or https protocol
Kind: global function
| Param | Type |
|---|---|
| url | string |
Example
const url = 'https://www.google.com';
const result = removeHttpProtocol(url);
console.log(result);
// => 'www.google.com'
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