Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
@kluntje/js-utils
Advanced tools
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.
npm install @kuntje/js-utils
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"));
Promise.<T>
Calls API and returns JSON as Promise
boolean
checks, if element is in given array
boolean
checks, whether given Array exists and has at least one element
Array.<T>
merge two given arrays by the given checker function
Array.<T>
pushes new Element to given array, if its not already in it
Array.<T>
removes specific Item from array and return new array
Date
Adds given amount of days to given date
string
Optionally Adds leading Zero to Numbers < 10
boolean
Checks whether given dates are equal
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
adds given classes to one or multiple elements
Element
| null
returns the first child of a specific parent matching the given selector
Array.<Element>
returns all children of a specific parent matching the given selector
string
returns current mediaQuery-name. e.g. "MQ2"
string
returns innerText of given Element
Element
| null
returns parent of specific class, if found
string
returns a random String to be used as ID
boolean
returns if a specific parent has a child matching the given selector
boolean
returns if a specific element has given class
boolean
checks, whether an element is in the viewport
boolean
checks, if target is NodeList
adds event with given parameters
removes all children of a specific parent matching the given selector
removes given class from element
removes event with given parameters
toggles given class on given element
Promise.<void>
resolves Promise after given timeout
Promise
returns a promise which resolves after the animationend event
Promise.<void>
waits for given event for a (optional) max-timeout
Promise.<void>
Promise that resolves, when the given component is initialized
Promise
returns a promise which resolves after the transitionend
event
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.
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.
*
returns nested value without throwing an error if the parent doesn't exist
boolean
compare two arguments, for object their toString values are compared
boolean
checks if provided argument is an object which has at least one entry in it.
Nullable.<T>
| Array.<T>
returns a deep link of the provided argument
Array.<T>
returns the argument wrapped in an array if it isn't array itself
string
returns stringified value for the given argument
string
removes all multi Whitespaces and Newlines in given string
number
returns number of words in a given text
string
removes all Whitespaces in given string
string
removes all Newlines in given string
string
removes multi Whitespaces in given string
string
function to convert texts to camelCase for example ti generate attribute names
string
converts the provided string to a kebab case (kebab-case)
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
function
iterates over all nodes in a node list (necessary because IE11 doesn't support .forEach * for NodeLists)
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));
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");
}
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");
}
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"
// }
// ]
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);
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"]
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);
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()}`;
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
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") // "2020-01-01T12:13:14.000+02:00"
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');
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');
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');
Kind: global function
Param | Type |
---|---|
node | Node |
index | Number |
nodeList | NodeListOf.<T> |
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);
string
returns innerText of given Element
Kind: global function
Param | Type |
---|---|
el | HTMLElement |
Example
const myArticle = document.querySelector('article');
const articleText = getInnerText(myArticle);
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');
string
returns a random String to be used as ID
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');
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")
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'));
boolean
checks, if target is NodeList
Kind: global function
Param | Type |
---|---|
target | any |
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);
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');
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');
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);
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);
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');
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;
// }
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');
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';
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();
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:
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 |
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));
*
Deprecated
returns nested value without throwing an error if the parent doesn't exist
Kind: global function
Returns: *
-
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;
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');
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;
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);
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"]
string
returns stringified value for the given argument
Kind: global function
Param | Type |
---|---|
arg | * |
Example
const submitData = toString(formData);
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);
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);
string
removes all Whitespaces in given string
Kind: global function
Param | Type |
---|---|
inputString | string |
Example
removeAllBS('Hello My World '); // HelloMyWorld
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);
string
removes multi Whitespaces in given string
Kind: global function
Param | Type |
---|---|
inputString | string |
Example
removeMultiBS('Hello My World'); // Hello My World
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";
string
converts the provided string to a kebab case (kebab-case)
Kind: global function
Param | Type |
---|---|
str | string |
Example
toKebabCase("keyValuePair") === "key-value-pair"
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'
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'
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}`))
π€ Frederik Riewerts frederik.riewerts@gmail.com
Give a βοΈ if this project helped you!
This README was generated with β€οΈ by readme-md-generator
FAQs
Collection of js helper functions
We found that @kluntje/js-utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.