view on
Github

JavaScript Helpers

Version


Documentation

Go to NPM →

Intro

JavaScript Helpers is a list of useful functions to make development easier.

Browsers Support

Desktop & Mobile versions of:


For compatibility with old browsers you may need to load some JS polyfills - depending on the imported functions ( from polyfill.io or else ):
Promise.prototype.finally AbortController fetch

<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=Promise.prototype.finally,AbortController,fetch"></script>

Usage

Install via NPM:

npm install javascript-helpers

and use as ES6 module loading the modules you need.
For example:

import { ajaxCall, delegateEvent, getElements } from 'javascript-helpers';

Note: Remember to use tree-shaking techniques to avoid importing all modules from JavaScript Helpers.

Helpers

addClass( elements, cssClasses )

Add the specified css class(es) to the specified HTML element(s).

Parameters:

  • elements: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • cssClasses: ( String ) One or more space-separated css classes to be added.

Return value:

Array of elements as returned by getElements from the passed elements.

Polyfills you may need: None

ajaxCall( options = {}[, canAbortOrController = false] )

Fire an AJAX call using fetch API ( see MDN documentation for options details ).

Parameters:

  • options: ( Object ) as per fetch options but you can also add these:

    {
        url: 'path-to/my-remote-service',
        timeout: 10000
    }
    

    Default options object is:

    {
        cache:          'no-store',
        credentials:    'same-origin',
        headers: {
                        'Content-Type': 'application/json'
        },
        method:         'GET',
        mode:           'same-origin',
        redirect:       'follow',
        timeout:        0,
        url:            location.href
    }
    

    Note that "headers" is passed as plain object.

  • canAbortOrController: ( AbortController or Boolean ) can be a new instance of AbortController or true/false

Return value:

Promise returned by fetch ( with body consumed depending on "Accept" request header or MIME type response header ).

If canAbortOrController is changed from default value, ajaxCall will return this instead:

{
    abort: Function,
    ready: Promise
}
  • abort: a function to abort the ajax call
  • ready: the Promise returned by fetch

Polyfills you may need:

  • AbortController
  • fetch
  • Promise.prototype.finally
arrayMove( array, fromIndex, toIndex )

Move one element of an array, from the specified index to the new one.

Parameters:

  • array: ( Array ) the list of elements

  • fromIndex: ( Number ) Index of the element you want to move

  • toIndex: ( Number ) Index you want the element to be moved to

Return value:

Modified array ( original array is not affected )

Polyfills you may need: None

deepFreeze( obj )

Apply Object.freeze recursively to freeze all nested objects too.

Parameters:

  • obj: ( Any )

Return value:

Same object given but freezed

Polyfills you may need: None

delegateEvent( ancestor, eventName, target, callback[, { data, options, useCapture = false } = {}] )

Attach a callback function to one event for all elements that match the target, now or in the future, based on ancestor root element(s).

All arguments are mandatory except last one.

Parameters:

  • ancestor: ( Document, NodeList | HTML Element | Selector | Array of HTML Elements ) Container element to which the event will be attached ( MUST exist when calling delegateEvent ).

  • eventName: ( String ) Event name on which the callback function will be triggered.

  • target: ( Selector ) CSS selector for the element(s) that will trigger the event ( these elements can exist or added in the future ).

  • callback: ( Function ) Function to be executed when the event is triggered. The keyword this is bound to the element matching the target.
    Callback has these parameters:

    • event: ( Event ) The original event object

    • data: ( Object ) data as passed to delegateEvent or undefined if not passed

  • [Object]: ( Object - optional ) An object with:

    • data: ( Object - optional ) Object to be passed to the callback function.

    • options: ( Object - optional ) Object to be passed to the event listener as third argument. See MDN doc

    • useCapture: ( Boolean ) Whether to use capturing phase or not for the event listener.

Polyfills you may need: None

emitEvent( elem, eventName[, eventOptions]  )

Dispatch an event on the specified element(s) and with specified event options.

Parameters:

  • elem: ( Document | NodeList | HTML Element | Selector | Array of HTML Elements )

  • eventName: ( String )

  • eventOptions: ( Object ) See eventInit on MDN documentation.
    Default:

    {
        bubbles: true
    }
    

Polyfills you may need: None

emitCustomEvent( elem, eventName[, eventOptions]  )

Dispatch a custom event on the specified element(s) and with specified event options, where you can add object detail.

Parameters:

  • elem: ( Document | NodeList | HTML Element | Selector | Array of HTML Elements )

  • eventName: ( String )

  • eventOptions: ( Object ) See customEventInit on MDN documentation.
    Default:

    {
        bubbles: true
    }
    

Polyfills you may need: None

fillForm( formEl, data[, skipFilledFields] )

Fill the fields in the specified form element using the passed data object.

Parameters:

  • formEl: ( NodeList | HTML Element | Selector )

  • data: ( Object ) Each key must match the name attribute of the filed.
    Values can be set depending on the field as follow:

    • checkbox ( single ): Boolean
    • checkbox / select ( multiple ): Array of Strings
    • radio: String
    • all others: String
  • skipFilledFields: ( Boolean ) Whether or not to skip fields with the value already set.

Return value:

HTML Element of the passed formEl

Polyfills you may need: None

getAge( dateString )

Get the age from the passed date.
-1 is returned if the argument is not a valid date.

Parameters:

  • dateString: ( String ) A valid date in format ISO 8601.
    YYYY-MM-DD | YYYY/MM/DD | YYYY MM DD

Return value:

Number

Polyfills you may need: None

getAgeBetween( dateString1, dateString2 )

Get the age between the passed dates. dateString1 must be greater than dateString2.
-1 is returned if one of the arguments is not a valid date.

Parameters:

  • dateString1: ( String ) A valid date in format ISO 8601.
    YYYY-MM-DD | YYYY/MM/DD | YYYY MM DD

  • dateString2: ( String ) A valid date in format ISO 8601.
    YYYY-MM-DD | YYYY/MM/DD | YYYY MM DD

Return value:

Number

Polyfills you may need: None

getDateSeparator( dateString[, checkIso8601separator = true] )

Get the character that is used as date separator.
null is returned if dateString is not a valid date.

Parameters:

  • dateString: ( String ) A valid date in format ISO 8601.
    YYYY-MM-DD | YYYY/MM/DD | YYYY MM DD

  • checkIso8601separator: ( Boolean ) Whether or not to check for the ISO 8601 date separators / - " "(space).

Return value:

String | null

Polyfills you may need: None

getElementOffset( element )

Get element offset top and left.

Parameters:

  • elements: ( NodeList | HTML Element | Selector )

Return value:

Object

Polyfills you may need: None

getElements( elements[, parent] )

Get an array of elements from the passed elements and, optionally, from a parent.

Parameters:

  • elements: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • parent: ( Document | NodeList | HTML Element | Selector | Array of HTML Elements )

Return value:

Array

Polyfills you may need: None

getFilledFields( formEl )

Get an array with all the form fields with a set value.

Parameters:

  • formEl: ( NodeList | HTML Element | Selector )

Return value:

Array

Polyfills you may need: None

getUniqueFields( formEl )

Get an array with all the unique form fields. Unique fields are retrieved by type and name attributes.

Parameters:

  • formEl: ( NodeList | HTML Element | Selector )

Return value:

Array

Polyfills you may need: None

getUrlParameter( [parameterName] )

Get the value of the specified parameter name.
If the parameter has no value, true is returned.
If parameterName is falsy, it will return all the parameters as array of objects ( key/value ).

Parameters:

  • parameterName: ( String )

Return value:

String | Boolean | Array

Polyfills you may need: None

isDomNode( node )

Check if the passed node is a DOM Node or not.

Parameters:

  • node: ( Any )

Return value:

Boolean

Polyfills you may need: None

isEmptyObject( obj )

Check if the passed obj is an empty object or not.

Parameters:

  • obj: ( Any )

Return value:

Boolean

Polyfills you may need: None

isFieldForChangeEvent( fieldEl )

Check if the passed fieldEl is eligible for a "change" event listener.

Parameters:

  • fieldEl: ( Any )

Return value:

Boolean

Polyfills you may need: None

isMobile

Check the user agent string to return if used device is mobile or not.
For detailed infos ( OS/Browser name, version etc... ) you can use device-detector-js or else.

Return value:

Boolean

Polyfills you may need: None

isNodeList( nodeList )

Check if the passed nodeList is a NodeList or not.

Parameters:

  • nodeList: ( Any )

Return value:

Boolean

Polyfills you may need: None

isPlainObject( obj )

Check if the passed obj is a plain object or not.

Parameters:

  • obj: ( Any )

Return value:

Boolean

Polyfills you may need: None

isValidDate( dateString )

Check if the passed dateString is valid date for ISO 8601 format.

Parameters:

  • dateString: ( Any )

Return value:

Boolean

Polyfills you may need: None

isValidEmail( emailString[, checkRfc5322 = false] )

Check if the passed emailString is valid email.

Parameters:

  • emailString: ( String )

  • checkRfc5322: ( Boolean ) Whether or not to check the passed email address against a RegExp 99.9% compliant with RFC5322 ( read this ).
    If set to false, it will check the email address against a simpler email RegExp ( read this ).

Return value:

Boolean

Polyfills you may need: None

isValidSelector( stringSelector )

Check if the passed stringSelector is valid CSS selector.

Parameters:

  • stringSelector: ( Any )

Return value:

Boolean

Polyfills you may need: None

mergeObjects( out )

Deep merge of objects, from left to right.
To return a completely new object, pass {} as first argument.
Arrays are not deeply merged but completely replaced.

Parameters:

  • out: ( Object )

Return value:

Object

Polyfills you may need: None

removeAllWhiteSpaces( string )

Remove all the white-spaces from the passed string.

Parameters:

  • string: ( String )

Return value:

String

Polyfills you may need: None

removeClass( elements, cssClasses )

Remove the specified css class(es) to the specified HTML element(s).

Parameters:

  • elements: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • cssClasses: ( String ) One or more space-separated css classes to be added.

Return value:

Array of elements as returned by getElements from the passed elements.

Polyfills you may need: None

removeMulitpleWhiteSpaces( string )

Remove consecutive multiple white-spaces from the passed string.
If two or more consecutive white-spaces are found, only one will remain.

Parameters:

  • string: ( String )

Return value:

String

Polyfills you may need: None

removeUrlHash()

Remove the hash from the url.

Polyfills you may need: None

replaceTemplateStrings( obj, string = '' )

Take each key of the passed obj and replace it in string with the corresponsing value.
Key names in string must be wrapped, like: {{name}}

Parameters:

  • obj: ( Object ) Object with keys and values to replace in stringHTML

  • string: ( String ) String containing wrapped keys to be replaced

Return value:

String

Polyfills you may need: None

runCallback( fn, data, options )

Run the passed function ( or array of functions ) passing to it/them data and options.

Parameters:

  • fn: ( Function | Array of Functions )

  • data: ( Object ) Data passed to each function.

  • options: ( Object ) Options passed to each function.

Polyfills you may need: None

runFunctionsSequence( functionsList, data, stopConditionFn )

Run the passed array of functions/promises as sequence and passing to them data.

Parameters:

  • functionsList: ( Array of Functions/Promises )

  • data: ( Object ) Data passed to each function/promise.

  • stopConditionFn: ( Function ) Function used as condition at each funciton/promise running to check if the sequence must stop or not.
    It must have a return statement: if true the execution will stop.

Return value:

Promise with all the data objects as returned by each function/promise ( if return statement is set ).

Polyfills you may need: None

serializeObject( obj )

Convert a JavaScript object to a url-encoded string.

Parameters:

  • obj: ( Object )

Return value:

String

Polyfills you may need: None

slideDown( element[, options[, callback]] )

Display the matched elements with a sliding motion.

Parameters:

  • element: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • options: ( Object )

    • delay: ( Number: 0 ) In milliseconds, determining how long to wait before the animation will run.
    • duration: ( Number: 400 ) In milliseconds, determining how long the animation will run.
    • easing: ( String: 'ease' ) Easing function to use for the transition.
    • displayValue: ( String: 'block' ) CSS display value to set after sliding motion.
  • callback: ( Function ) Executed once the animation is complete, called once per matched element.

Polyfills you may need: None

slideToggle( element[, options[, callback]] )

Display or hide the matched elements with a sliding motion.

Parameters:

  • element: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • options: ( Object )

    • delay: ( Number: 0 ) In milliseconds, determining how long to wait before the animation will run.
    • duration: ( Number: 400 ) In milliseconds, determining how long the animation will run.
    • easing: ( String: 'ease' ) Easing function to use for the transition.
    • displayValue: ( String: 'block' ) CSS display value to set after sliding motion.
  • callback: ( Function ) Executed once the animation is complete, called once per matched element.

Polyfills you may need: None

slideUp( element[, options[, callback]] )

Hide the matched elements with a sliding motion.

Parameters:

  • element: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • options: ( Object )

    • delay: ( Number: 0 ) In milliseconds, determining how long to wait before the animation will run.
    • duration: ( Number: 400 ) In milliseconds, determining how long the animation will run.
    • easing: ( String: 'ease' ) Easing function to use for the transition.
  • callback: ( Function ) Executed once the animation is complete, called once per matched element.

Polyfills you may need: None

setUrlHash( hashValue )

Set the passed hashValue as url hash.

Parameters:

  • hashValue: ( String )

Polyfills you may need: None

toCamelCase( string )

Convert the passed string to a camel-case string (eg: "helloMyFriend").

Parameters:

  • string: ( String )

Return value:

String

Polyfills you may need: None

toggleClass( elements, cssClasses, force )

Toggle the specified css class(es) to the specified HTML element(s).

Parameters:

  • elements: ( NodeList | HTML Element | Selector | Array of HTML Elements )

  • cssClasses: ( String ) One or more space-separated css classes to be toggled.

  • force: ( Boolean ) If included, turns the toggle into a one way-only operation. If set to false, then css class(es) will only be removed, but not added. If set to true, then css class(es) will only be added, but not removed.

Return value:

Array of elements as returned by getElements from the passed elements.

Polyfills you may need: None

toKebabCase( string, useAllCaps = false )

Convert the passed string to a kebab-case string (eg: "hello-my-friend").

Parameters:

  • string: ( String )

  • useAllCaps: ( Boolean ) Whether or not to transform the string in all-caps.

Return value:

String

Polyfills you may need: None

toPascalCase( string )

Convert the passed string to a pascal-case string (eg: "HelloMyFriend").

Parameters:

  • string: ( String )

Return value:

String

Polyfills you may need: None

toSnakeCase( string, useAllCaps = false )

Convert the passed string to a snake-case string (eg: "hello_my_friend").

Parameters:

  • string: ( String )

  • useAllCaps: ( Boolean ) Whether or not to transform the string in all-caps.

Return value:

String

Polyfills you may need: None

webStorage

This is useful to check if web storage is available in the browser ( local storage and session storage ) and to extend its functionalities.
Call webStorage.extend() will add these new methods for web storage ( if web storage is available ):

  • Storage.prototype.getObject( name )
    • name: ( String ) The name for the web storage to retrieve.

    This method will return a JavaScript object with the saved web storage infos.

  • Storage.prototype.setObject( name, object )
    • name: ( String ) The name for the web storage.

    • object: ( Object ) A JavaScript object to store in web storage.

  • Storage.prototype.mergeItem( name, object )
    • name: ( String ) The name for the web storage to merge the object in.

    • object: ( Object ) A JavaScript object to store in web storage.

Return value:

{
    isAvailable: Boolean,
    extend: Function
}

Polyfills you may need: None

Changelog

  • 2.0.0
    • Drop support for IE
    • Added "getElementOffset"
    • Added "slideDown"
    • Added "slideToggle"
    • Added "slideUp"
    • Added "toggleClass"
    • Added method "extend" to "webStorage" to let you call it manually and added "mergeItem" to methods added from "webStorage.extend()"
    • Updated "getElements" to accept Array of HTML Elements as "elements" and added "parent" parameter
    • Internal improvements
    • BREAKING CHANGES:
      • "delegateEvent": changed parameters order and type
      • "isValidEmail": changed value of optional parameter "checkRfc5322", now defaults to false
      • "webStorage": web storage new methods are not automatically added
      • Removed "ajaxCallXhr"
      • Removed "checkDirtyField"
      • Removed "checkFormElement"
  • 1.4.2
    • Fixed bug on "ajaxCall" when response is not ok
  • 1.4.1
    • Fixed bug for "emitEvent" and "emitCustomEvent" where parameter "eventOptions" was not used properly
    • Improved "emitEvent" and "emitCustomEvent" to let you pass NodeList, HTML Element or CSS Selector as first argument
  • 1.4.0
    • Added "arrayMove"
    • Added "delegateEvent"
    • Added "replaceTemplateStrings"
    • DEPRECATED features:
      • checkDirtyField
      • checkFormElement
  • 1.3.0
    • Added "emitEvent"
    • Added "emitCustomEvent"
    • Added "deepFreeze"
    • Changed "ajaxCall" to make it manually abortable
    • Updated doc with polyfills you may need for each function
    • Minor improvements
  • 1.2.1
    • Improved alternative RegExp for "isValidEmail"
  • 1.2.0
    • Added "ajaxCallXhr", "isValidEmail", "toPascalCase"
    • Improved "ajaxCall", now method text() is used also to consume response if header Content-Type is empty or 'application/javascript'
    • Fixed bug in "toCamelCase", "toKebabCase", "toSnakeCase" by trimming string at beginning
  • 1.1.2
    • Fixed bug in "isValidDate"
    • Updated dev dependencies
  • 1.1.1
    • Fixed bug in "runFunctionsSequence" when called with empty array of functions
  • 1.1.0
    • Added "isMobile"
    • Refactored "fillForm"
    • Improved "mergeObjects" and "checkFormElement"
    • "addClass", "checkDirtyField", "fillForm" and "removeClass" now return the passed element(s)
  • 1.0.1
    • First release

Bugs

If you find a bug, please report it here