Skip to content

A zero-dependency collection of utility functions that can be imported as a module or be added to any website using a minified js file which simplifies developing websites.

License

Notifications You must be signed in to change notification settings

harshankur/vanillautils

Repository files navigation

Vanilla Utils

This is a zero-dependency collection of utility tools that will help development on vanilla-js a bit easier for you. I have always appreciated the no-framework idea for most small projects which do not require a lot of maintenance. And these are the sets of tools that I have always had in my projects in some way or form. I have compiled them here with improvements such that they are helpful in a more macroscopic level. I will keep updating it with more tools.

Access it by using this library. Or you can use it in your frontend code like this

<script src="https://mirror.harshankur.com/vanillaUtils.min.js" crossorigin="anonymous"><script>

Below is the documentation for this project.

Functions

createElement(tagName, [attributes])HTMLElement

Creates an element with a given attribute map in the argument for a given tagName.

openLink(url, [newTab])void

Opens the link provided in the argument 'url'. Based on the other argument 'newTab', it either opens it in the same tab or in a new tab. NOTE: In the case of trying to open this url in a new tab, the browser might first ask the user to enable popups for this website instead of directly opening the link.

downloadLink(url)void

Downloads the content of the url passed in the argument. NOTE: You can only trigger download of a url which is in the same domain as the current one. There is Cross-Site access for downloads. If you pass a url from another domain, the browser usually just opens the file on the same tab which might result in loss of unsaved data in the current page.

guessMimeType(bytes)string

Guess the MIME type based on the initial bytes of a file.

downloadFileFromBytes(bytes, name, [type])void

Saves the content of the byteArray passed in the argument with its filename passed in the argument.

fetchRequest(url, [config])Promise.<any>

Fetch handler for a request with body.

setCookie(key, value, [config])void

Sets cookie on the browser for the given key and value for the given duration

getCookie(key)string

Fetches cookie value for a given key.

removeCookie(key)void

Remove cookie for a given key.

toPromise(fn, args)Promise.<any>

This takes a function and returns a promisied version of it. Basically it resolves after this fn is executed. It is helpful primarily when one is switching over multiple cases and some of them do not return a promise but it is easier to handle all the cases in promises.

debounce(fn, t)function

Debounces a function, i.e., ignored repeated calls for a function. It rather takes the last call while it is waiting.

Typedefs

FetchConfig : Object
CookieConfig : Object

createElement(tagName, [attributes]) ⇒ HTMLElement

Creates an element with a given attribute map in the argument for a given tagName.

Kind: global function

Param Type Default Description
tagName string A tag name for this new element to be created.
[attributes] Object.<string, any> {} We will use this object's keys as attributes for the element and its values as the attribute values.

Example

const attributes = {
    class: 'class1 class2',
    id: 'id1',
    style: '{ display: "flex"; }',
    'data-region': 'Germany'
};
const element = createElement('div', attributes);
// <div class="class1 class2" id="id1" style="{ display: "flex"; }" data-region="Germany"></div>

Example

const attributes = {
    href: 'https://blog.harshankur.com',
    target: '_blank'
};
const element = createElement('a', attributes);
// <a href="https://blog.harshankur.com" target="_blank"></a>

openLink(url, [newTab]) ⇒ void

Opens the link provided in the argument 'url'. Based on the other argument 'newTab', it either opens it in the same tab or in a new tab. NOTE: In the case of trying to open this url in a new tab, the browser might first ask the user to enable popups for this website instead of directly opening the link.

Kind: global function

Param Type Default Description
url string The url that you want to open on the client's browser.
[newTab] boolean false Flag whether to open this url in a new tab. Please note that passing this true might get the new link (popup) blocked depending on the browser settings.

Example

openLink("https://github.com/harshankur");

Example

openLink("https://github.com/harshankur", true);

downloadLink(url) ⇒ void

Downloads the content of the url passed in the argument. NOTE: You can only trigger download of a url which is in the same domain as the current one. There is Cross-Site access for downloads. If you pass a url from another domain, the browser usually just opens the file on the same tab which might result in loss of unsaved data in the current page.

Kind: global function

Param Type Description
url string The url from which you wish to trigger a content download.

Example

downloadLink("https://mirror.harshankur.com/vanillaUtils.min.js");

guessMimeType(bytes) ⇒ string

Guess the MIME type based on the initial bytes of a file.

Kind: global function
Returns: string - The guessed MIME type or 'application/octet-stream' if unknown.

Param Type Description
bytes Uint8Array The byte array representing the file content.

guessMimeType~signatures : Object.<string, string>

Known file signatures mapped to their corresponding MIME types.

Kind: inner constant of guessMimeType

guessMimeType~getHexString(byteArray) ⇒ string

Converts a byte array to a hexadecimal string.

Kind: inner method of guessMimeType
Returns: string - The hexadecimal string representation of the byte array.

Param Type Description
byteArray Uint8Array The byte array to convert.

downloadFileFromBytes(bytes, name, [type]) ⇒ void

Saves the content of the byteArray passed in the argument with its filename passed in the argument.

Kind: global function

Param Type Description
bytes Uint8Array File bytes.
name string The name of the file in the download
[type] string File Mimetype

Example

downloadFileFromBytes(<bytes>, 'myFile.pdf');

fetchRequest(url, [config]) ⇒ Promise.<any>

Fetch handler for a request with body.

Kind: global function
Returns: Promise.<any> - Returns a Promise for the fetch request.

Param Type Default Description
url string Url to make this fetch request.
[config] FetchConfig {} Config for this fetch request.

Example

fetchRequest('https://mirror.harshankur.com/vanillaUtils.min.js')
// GET https://mirror.harshankur.com/vanillaUtils.min.js

Example

const params = {
    method: 'POST',
    header: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name: "Harsh Ankur" })
};
fetchRequest('https://post-example.com/registerName', params);
// POST https://post-example.com/registerName -H "Content-Type: application/json" -d '{ "name": "Harsh Ankur" }'

setCookie(key, value, [config]) ⇒ void

Sets cookie on the browser for the given key and value for the given duration

Kind: global function

Param Type Default Description
key string Key of the cookie
value string Value to be set for this cookie
[config] CookieConfig {} [OPTIONAL] Configuration for settings cookies

Example

setCookie("key1", "value1");
// Setting session specific cookie for key1: value1

Example

setCookie("key2", "value2", { expires: 30, path: '/' });
// Setting key2: value2 cookie on the root domain that expires in 30 days.

getCookie(key) ⇒ string

Fetches cookie value for a given key.

Kind: global function
Returns: string - Value of the cookie for the corresponding key.

Param Type Description
key string Key of the cookie.

Example

const storedValue = getCookie("key1");
// "value1"

Example

const storedValue = getCookie("key2");
// "value2"

removeCookie(key) ⇒ void

Remove cookie for a given key.

Kind: global function

Param Type Description
key string Key of the cookie

Example

getCookie("key1");
// "value1"
removeCookie("key1");
getCookie("key1");
// ""

toPromise(fn, args) ⇒ Promise.<any>

This takes a function and returns a promisied version of it. Basically it resolves after this fn is executed. It is helpful primarily when one is switching over multiple cases and some of them do not return a promise but it is easier to handle all the cases in promises.

Kind: global function
Returns: Promise.<any> - Promise that will be resolved once the fn function is executed.

Param Type Description
fn function Function that is needed to be promisied.
args Array.<any> Array of arguments to be called for this function.

debounce(fn, t) ⇒ function

Debounces a function, i.e., ignored repeated calls for a function. It rather takes the last call while it is waiting.

Kind: global function

Param Type Description
fn function Function needed to debounce
t number milliseconds delay for debouncing.

FetchConfig : Object

Kind: global typedef
Properties

Name Type Description
[method] 'DELETE' | 'GET' | 'POST' | 'PUT' Method of the fetch call. Default is 'GET'.
[mode] 'no-cors' | 'cors' | 'navigate' | 'websocket' | 'same-origin' Cross-Origin Mode. Default is 'cors' if the fetch is created using Request constructor. Otherwise it is 'no-cors'.
[cache] 'default' | 'no-cache' | 'reload' | 'force-cache' | 'only-if-cached' Cache Policy. Default is 'default'.
[credentials] 'include' | 'same-origin' | 'omit' Credentials Policy. Default is 'same-origin'.
[redirect] 'manual' | 'follow' | 'error' Redirect Policy. Default is 'follow'.
[referrerPolicy] 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url' Refferer Policy. Default is 'no-referrer-when-downgrade'.
[headers] object Header for this fetch request. Default is an empty object.
[body] object | string Body for this fetch request. Body data type must match "Content-Type" header.

CookieConfig : Object

Kind: global typedef
Properties

Name Type Description
[expires] number Number of DAYS after which this cookie will be expired. If not specified, it would mean that the cookie is session-specific.
[path] string Indicates the path that must exist in the requested URL for the browser to send the Cookie header (e.g., '/', '/mydir'). If not specified, it defaults to the current path of the current document location.
[samesite] string Prevents the browser from sending this cookie along with cross-site requests. Possible values are lax, strict or none. Strict prevents from sending to cross-site requests. Lax allows a few basic cross-site requests but prevents many Cross-Site Requesst Forgery attacks. Default is None which implies no restriction.
[secure] boolean Specifies that the cookie should only be transmitted over a secure protocol. Default is true which would mean that this cookie will be sent over only in secure communications.

About

A zero-dependency collection of utility functions that can be imported as a module or be added to any website using a minified js file which simplifies developing websites.

Resources

License

Stars

Watchers

Forks

Packages

No packages published