cutlery.js

A set of useful javascript and sass tools – view on npm

node

Simple function to return a node

node(node[, multiple = false])

  • node string: css-selector of an element
  • multiple boolean: return single node or node-list (querySelectorAll)

/**
 * in this example you would have a list of cards on a page,
 * set the second parameter to `true` to return a nodelist, false by default
*/
const footer = node('#app footer');
const cards = node('#app > .cards > .card', true); 
edit on GitHub

returnNode

Checks if an element is a node, if not it returns a node

returnNode(node[, multiple = false])

  • node string | node: a css-selector or an actual node
  • multiple boolean: return single node or node-list (querySelectorAll)

A good function when you have an other function where the input can be a node or a css-selector, but you are not shure which.

/**
 * This is an example where the function is being used in
*/

const returnText = (input) => {
    const element = returnNode(input , true); // no mather what a developer would give as input parameter, the function would return an element
    return element.innerText;
}

const $pane = document.querySelector('#app .pane');
const paneText = returnText($pane);

const userDetails = returnText('#app .user > .user__details');
edit on GitHub

returnTag

Returns the tagname of an element

returnTag(node)

  • node string | node: a css-selector or an actual node

const all = document.querySelectorAll('*');
all.forEach(el => {
    console.log(returnTag(el));
})
edit on GitHub

fieldTypes

Returns the fieldtype of an input-element

fieldTypes(node)

  • node string | node: a css-selector or an actual node

When the node you assign to the function is a form-element, than the function will return a Map object. The keys are the name-attribute-values of the input-elements. Input-elements without a name-attribute will be ignored.

In this function is the returnTag-function used.

const inputField = fieldTypes('#newUserForm > #newUserName');

const form = document.querySelector('#newUserForm');
const fields = fieldTypes(form);
edit on GitHub

eventCallback

Execute code when a eventlistener is triggered

eventCallback(node, callback[, action = true])

  • node string: a css-selector
  • callback function: the code that will be executed, returns the event target
  • action boolean: set to false if the element that has to be detected isn't defined by a data-action attribute

You would use this function if you want to limit the eventlisteners you add to a page.

How you would use this function

  • Add it inside an eventlistener
  • Set the selector-parameter to the css-selector of the element that you want to detect
  • Add code that has to be executed when the element is detected

Examples

Stand-alone function, outside eventlistener;

<button data-do="hideMenu">hide menu</div>
<div class="menu">
    menustuff...
</div>
eventCallback('btn[data-do="hideMenu"]', (target) => {
    hideSomething(target);
}, false)

How it works

When the function is launched it watches the target element of the eventlistener. If the css-selector of this element matches the given selector the callback will be executed.

So you could have a couple of buttons, with like a data-attribute, with inside them an icon and some span-elements. What would happen in a normal case: you'd click inside the button, on a span. But on the click event you want to return the value of the data-attribute. Since you clicked on that span element inside the button it would return nothing and probably break a function or two since it doesn't returns a value.

Now with this function you'd click inside the button, but with the css-selector set to something like button[data-do-on-click] you could click inside the button, on a span, the function would only return the button, so the css-selector works like a filter and will select the element closest to it.

For more information about this aspect of the function read about the closest-function.

edit on GitHub

new Element

Easily create new nodes

new Element(tagname)

  • tagname string: the tagname of the node you want to create

Steps

Create new instance

const element = new Element('div');

Add (html-)content
You can set the innerHTML of the element using the inner-function;

element.inner(`
    <div class="card__header"><h3>Card-title</h3></div>
    <div class="card__body">Some content</div>
    <div class="card__footer"><button data-action="close"></button></div>
`)

You can also use the return-function to set the innerHTML.

element.return().innerHTML = `
    <div class="card__header"><h3>Card-title</h3></div>
    <div class="card__body">Some content</div>
    <div class="card__footer"><button data-action="close"></button></div>
`;

Add classes (array)
Add an array directly in the function

element.class(['card', 'animate__animated', 'animate__zoomIn']);

or create an array first

const classes = ['card', 'animate__animated', 'animate__zoomIn'];
element.class(classes);

Set attributes (nested arrays)
Set attributes for a node as nested arrays. You can also make an array first, outside the function and then add the variable to the function.

element.attributes([
    ['data-id', 'fJEhegfHJEjknekiz'],
    ['data-tooltip', 'hover over this card']
]);

Append (css-selector|node)
Append the node to another node. You can append the element multiple times to the DOM.

element.append('main > .card__list');

Prepend (css-selector|node)
Prepend the node to another node. You can append the element multiple times to the DOM.

element.prepend('main > .card__list');

The Return of the Node
Return the node so you can easily use it in other functions for example.

element.return();

When you use the return-function you can manipulate the object as you would with a normal node. (See the inner-function for another example)

//
element.return().

// remove when needed
element.return().remove();

Log
You can easily log the element so you can evaluate the result.

element.log();

Use the return-function
You can use the return-function so you can add the node somewhere

edit on GitHub

connection

connection

Get state

Get the connectionstate once, but you can call it as much as you want

connection.state(); // returns integer

States
The integer that is returned corresponds to a certain status

  • 0: connection offline
  • 1: slow/bad connection
  • 2: good connection
  • 3: strong connection

Watch the connection

The watch function let's you set an eventlistener for the users' connection. It will execute the callback you set, every time the users' connection the changes.

The watch function returns a integer in the same way the method above does.

const connectionStateText = (state) => {
    return {
        0: 'offline',
        1: 'slow/bad',
        2: 'good',
        3: 'strong'
    }[state];
}

connection.watch((state) => {
    const text = connectionStateText(state);
    console.log(`your connection is ${text}`);
})
edit on GitHub

new Api

Fetch data end choose the output format

new Api(url [, options = {method: 'GET'}])

  • url string: the source of the file you want to fetch
  • options object: options you can set for the fetch web Api

Create an instance

Begin by creating a new insxtace

In these cases the classes are used inside an async function

// since the class returns a promise use async await
const corona = await new Api('https://api.thevirustracker.com/free-api?countryTotal=BE');

Get the data

You have several output-formats you can choose from

Status
Get the response data from a call

await corona.status();

JSON
This will do a fetch call, convert the data to JSON and return it

await corona.JSON();

TEXT
Returns the response data as text so you can manipulate it as you want

await corona.TEXT();

Coming soon: NODE
If you need to fetch a webpage this method will return nodes

await corona.NODE()

Every time you call an output-format, the data is fetched, keep this is mind when you have a limit on calls. We'll try to fix this as soon as possible.

edit on GitHub

getFormData

Retrieve formdata, without submitting

getFormData(form)

  • form string | node: the form itself as css-selector or an actual node, most of the time this is the event target of an (submit) eventlistener

Just add the form as parameter and when the function is called it returns a Map object.

The map keys are the name-values of the form elements. Input-elements that don't have a name-attribute will be ignored since the build in FormData API in browsers requires a name-attribute-value.

Examples

Stand-alone function, outside eventlistener;

const newUserForm = document.querySelector('#newUserForm');
const newUserData = getFormData(newUserForm); // returns Map object

Combined with an eventlistener and eventCallback-function;

window.eventListener('submit', () => {
    eventCallback('#newUserForm', (target) => {
        const newUserData = getFormData(target); // returns Map object
    }, false)
})

Why this function

It's far more convenient than manually selecting all form elements and getting their values.

Just one function returns all the values.

Return of input-types

This is how values will be returned from different types of input fields.

text | passwords | textarea
Just text will be returned

checkbox
Returns the value if checked or else false

number | ranges
These values will be converted in numbers and returned

file
A file field will return all properties of this field as an json object.

edit on GitHub

Setup cutlery.js


Javascript

Node — ESM (recommended)

Add the package to your project

npm i cutleryjs --save

Import it in a file

import {node, Element, ...} from 'cutleryjs'
Node – require

We've added support for older versions of node

Add the package to your project

npm i cutleryjs --save

Import it in a file with the require function

const {node, Element, ...} = require('cutleryjs/dist/js/legacy.min.js')
// this directory will change in the next big update
CDN

Import cutlery directly in a javascript-file using ESM.

import {node, Element, ...} from 'https://unpkg.com/cutleryjs/dist/js/index.js'

CSS

Import SCSS

Import the included css as scss in your project

@import '~/node_modules/cutleryjs/src/scss/index.scss';

If you use Parcel then you can include the scss file directly in your html file

<link rel="stylesheet" href="~/node_modules/cutleryjs/src/scss/index.scss">

CDN

Add the included css by adding a stylesheet to your project pages

<link rel="stylesheet" href="https://unpkg.com/cutleryjs/dist/css/index.css">
edit on GitHub

event

Add an eventlistener to a single element

event(eventtype)

  • eventtype string: the name of the eventtype, works with the "on"-prefix and without

This function is easy when you don't want to define a full eventlistenerfunction with callback in it. Instead the callback is directly coupled to the element and the eventtype.

In these examples the node function is used.

Use

You don't need to import the event function. Just by importing the file or another function the event function is loaded.

Just select a node, chain the event method to it and set the callback-function.

node('body').event('onclick')(() => {
    console.log('the body node was clicked')
})

You can also leave the "on" prefix for the event type out.

node('body').event('click')(() => {
    console.log('the body node was clicked')
})

Note that the callback-functions is nameless. The callback-function is directly added after the event function.

Use with multiple nodes

This function is made to work with a single node, create a loop to use it with multiple nodes (like when you use querySelectorAll).

// true in the node function-function means you want to get all nodes with this selector
node('.clickable', true).forEach((el) => {
    el.event('click')(() => {
        console.log('the body node was clicked')
    })
})
edit on GitHub