Skip to content

Latest commit

 

History

History
3375 lines (2663 loc) · 131 KB

documentation.md

File metadata and controls

3375 lines (2663 loc) · 131 KB

Members

prototype

Converts most of the functions of Bijou.js to prototype functions. Note that you have to call this function to add the prototypes.

_temp : Object

Bijou.js source documentation. In the Bijou namespace you will find the documentation for all of the functions in Bijou.js, if you have any questions, suggestions or bug reports pleast make an issue (here)[https://github.com/bijou-js/bijou.js/issues/new/choose]. Best of luck! Thanks for using Bijou.js! --Explosion--

Objects

array : object

The array namespace of Bijou.js

color : object

The color namespace of Bijou.js

date : object

The date namespace of Bijou.js, containing functions to format dates, do math with them and more!

element : object

The element namespace of Bijou.js, containing functions to create elements from query selectors, enable custom right click options, test if an element is on screen, replace the text of an element without altering it's styling, and much more!

event : object

The event namespace of Bijou.js, containing functions to listen and dispatch events, such as scroll stop, outside click, and multiple event listeners.

function : object

The function namespace of Bijou.js, containing functions to work with functions themselves, such as debouncing, throttling, memoizing, currying, timing and much more!

math : object

The math namespace of Bijou.js, containing functions to validate credit card numbers, animate with JavaScript, generate unique id's and much more!

object : object

The object namespace of Bijou.js, for stuff like flattening nested objects, cloning, merging, and even listening to changes to objects!

string : object

The string namespace of Bijou.js, containing functions to map strings, remove accents from strings, speak text, syntax highlight JS, HTML and CSS and much more!

utility : object

The utility namespace of Bijou.js, containing utilities to do many things, such as playing audio, fetching JSON, preloading images and much more.

Functions

node()

Tests if the user is using Node.js or not and throws an error in specific functions (that require the DOM) if they are.

Typedefs

averageByFnNumber
eachCallback : function
replaceTextCallbackString
eventListenersCallbackundefined
sortTableCallbackString
scrollStopCallbackundefined
juxtCallbackArray.<array>
spreadCallbackany
listenCallbackundefined
mapObjKeysCallbackString
mapObjValuesCallbackany
animateNumCallbackNumber
animateCallbackundefined
mapCallback : function
manipulateVideoStreamFunctionObject

prototype

Converts most of the functions of Bijou.js to prototype functions. Note that you have to call this function to add the prototypes.

Kind: global variable

Param Type Description
options Object The options to use, supports overwrite (boolean of whether to overwrite existing prototypes), and try, (boolean for whether to wrap in a try..catch)

_temp : Object

Bijou.js source documentation. In the Bijou namespace you will find the documentation for all of the functions in Bijou.js, if you have any questions, suggestions or bug reports pleast make an issue (here)[https://github.com/bijou-js/bijou.js/issues/new/choose]. Best of luck! Thanks for using Bijou.js! --Explosion--

Kind: global variable
Author: Explosion-Scratch, GrahamSH-LLK, Bijou.js contributors

array : object

The array namespace of Bijou.js

Kind: global namespace

array.exports.count(arr) ⇒ Object

Counts the items in an array, returning a separate count for each object.

Kind: static method of array

Param Type Description
arr Array The array to count items in.

Example

_$.count(['a', 'b', 'c', 'd', 'e', 'f'])//{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1}

//But if you have multiple items:
_$.count(['a', 'a', b', 'b', 'c', 'd', 'e']);//{'a': 2, 'b': 2, 'c': 1, 'd': 1, 'e': 1}

array.exports.arrayDiff(a1, a2) ⇒ Array | String

Returns the difference between two arrays or strings.

Kind: static method of array
Returns: Array | String - The difference between two arrays or strings.

Param Type Description
a1 Array | String The first array or string
a2 Array | String The 2nd array or string.

Example

console.log(_$.arrayDiff(['a', 'b'], ['a', 'b', 'c', 'd'])); // ["c", "d"]

array.exports.diff(text1, text2) ⇒ Array.<Array.<number>>

Gets the difference between two strings.

Kind: static method of array
Returns: Array.<Array.<number>> - An array of arrays, each array in the main array contains 2 numbers, the start and then end of the difference.

Param Type Description
text1 String The 1st text to compare
text2 String The 2nd text to compare with the 1st one.

Example

console.log(_$.diff("hello earthlings", "hello world"); // [[6,8],[9,16]]

array.exports.remove(array, item)

Removes an item from the array specified.

Kind: static method of array

Param Type Description
array Array The array to remove the item from.
item * The item to remove.

Example

console.log(_$.remove([5, 4, 3, 2, 1], 4)); // [5, 3, 2, 1]

array.exports.spliceArrayBuffer(arr, start, end, [endian]) ⇒ Number

Splices an ArrayBuffer.

Kind: static method of array
Returns: Number - The hex representation of part of the ArrayBuffer.

Param Type Default Description
arr ArrayBuffer | Buffer The ArrayBuffer to splice.
start Number The start index.
end Number The end index.
[endian] Boolean false Whether to use big endian or not.

array.exports.flatten(array, [level]) ⇒ Array

Flattens an array level times.

Kind: static method of array
Returns: Array - The flattened array.

Param Type Default Description
array Array The array to flatten.
[level] Number 1 The number of iterations to flatten it.

Example

console.log(_$.flatten(['a', 'b', ['c', 'd']])); // ['a', 'b', 'c', 'd'];

array.exports.nFlatten(arr) ⇒ Array

Flattens an array recursively.

Kind: static method of array
Returns: Array - The flattened array.

Param Type Description
arr Array The array to flatten.

Example

console.log(_$.nFlatten([5,[[9,4],0],[7,6]])); // [5,9,4,0,6,7]

array.exports.contains(array, item) ⇒ Boolean

Returns whether the specified array or string contains the item given.

Kind: static method of array
Returns: Boolean - True or false depending on if the array contains that item.

Param Type Description
array Array The array to test with.
item String The item to see if the array contains.

Example

console.log(_$.contains([1,2,3,4,5], 3)); // true

array.exports.shuffleArray(array) ⇒ Array

Shuffles an array

Kind: static method of array
Returns: Array - The shuffled array.

Param Type Description
array Array The array to shuffle.

Example

let array = [1,2,3,4,5];
console.log(_$.shuffleArray(array)); // e.g. [2,4,1,5,3]

array.exports.splice(array, index, item, [remove]) ⇒ String | Array

Splice but also for strings

Kind: static method of array
Returns: String | Array - the spliced array or string

Param Type Default Description
array String | Array The array or string to operate on
index Number The index to splice
item * The item
[remove] Number 0 How many to remove.

Example

console.log(_$.splice("hello earthlings", 5, " puny")); // "hello puny earthlings"

array.exports.unionArrays(x, y) ⇒ Array

Joins two arrays together and removes duplicate items.

Kind: static method of array
Returns: Array - The joined array from the two other arrays.

Param Type Description
x Array The first array to join.
y Array The second array to join.

Example

console.log(_$.unionArrays([1,2,3,4], [4,5,6])); // [1,2,3,4,5,6]

array.exports.averageBy(arr, fn) ⇒ Number

averageBy

Kind: static method of array
Returns: Number - The average of the array.

Param Type Description
arr Array.<number> The array to average
fn averageByFn The function to apply to each item of the array.

Example

Logs the average of the first 4 square numbers:
console.log(_$.averageBy([1,2,3,4], (v) => v ** 2)); // 7.5

array.exports.uniqueArray(array) ⇒ Array

Removes duplicates from an array

Kind: static method of array
Returns: Array - The array with no duplicates.

Param Type Description
array Array The array to remove duplicates from.

Example

console.log(_$.uniqueArray([1,1,2,3,4,4,4,5,6)); // [1,2,3,4,5,6]

array.exports.each(array, callback) ⇒ Array.<any>

For each item in an array, run a callback with it.

Kind: static method of array
Returns: Array.<any> - The array passed at the beginning.

Param Type Description
array Array | String | Number The array, string or number to run the callback with.
callback eachCallback The callback function to run on the array items.

Example

_$.each(new Array(6), (array_item, i) => console.log(i));
// 0
// 1
// 2
// 3
// 4
// 5

color : object

The color namespace of Bijou.js

Kind: global namespace

color.exports.rgbToHex(rgb) ⇒ String

Converts a rgb(a) color to hex.

Kind: static method of color
Returns: String - The hex color.

Param Type Description
rgb String The string of RGB colors.

Example

console.log(_$.rgbToHex("rgb(255,255,255)")); // "#ffffff"

color.exports.hexToRGB(hex) ⇒ String

Converts a hex code to a RGB color.

Kind: static method of color
Returns: String - The RGB color converted from the hex code.

Param Type Description
hex String The hex code to convert.

Example

console.log(_$.rgbToHex("#ffffff")); // "rgb(255,255,255)"

color.exports.blendColors(color1, color2, [percent]) ⇒ String

Blends two colors through additive blending by a percentage.

Kind: static method of color
Returns: String - The blended color (A hex code).

Param Type Default Description
color1 String The hex code of the first color to be blended
color2 String The hex code of the second color to be blended.
[percent] Number 50 A number between 0 and 100 of the percentage to blend the two colors, 0 being completely the first color and 100 being completely the second color.

Example

console.log(_$.blendColors("#ffffff", "#000000", 80)); // #333333

color.exports.randomColor() ⇒ String

Generates a random hex color.

Kind: static method of color
Returns: String - A random Hex color
Example

console.log(_$.randomColor()); // e.g. #5bf462

color.exports.lightenColor(col, amt) ⇒ String

Lighten or darken a color by a certain amount

Kind: static method of color
Returns: String - The color lightened.

Param Type Description
col String The color to lighten/darken
amt Number The amount to lighten the color (out of 255).

Example

_$.lightenColor("#000000", 50); // #323232

color.exports.lightOrDark(color) ⇒ Object

Tests if a color is light or dark and returns an object representation.

Kind: static method of color
Returns: Object - An object that represents if the color is light or dark and how much. The object key "hsp" represents a value out of 255 of how light the color is and the object's key "lightOrDark" is a string (Either "light" or "dark") of whether the color is light or dark.

Param Type Description
color string The hex color to test.

Example

if (_$.lightOrDark("#333333").lightOrDark === 'dark'){
    document.querySelector("DIV").style.color = "white";
  } else {
      document.querySelector("DIV").style.color = "black";
  }

date : object

The date namespace of Bijou.js, containing functions to format dates, do math with them and more!

Kind: global namespace

date.exports.dayName([date], [locale]) ⇒ String

Returns the name of the weekday from the Date object specified.

Kind: static method of date
Returns: String - The day name from the date.

Param Type Default Description
[date] Date new Date() The date object to use.
[locale] String en-US The locale to use.

Example

console.log(_$.dayName)); // e.g. "Friday"

date.exports.formatMilliseconds(ms) ⇒ String

Formats a number of milliseconds

Kind: static method of date
Returns: String - The string of formatted milliseconds.

Param Type Description
ms Number | String The number of milliseconds to format to a string.

Example

console.log(_$.formatMilliseconds(1324765128475)); // "1 century, 7 years, 2 days, 22 hours, 18 minutes, 48 seconds, 475 milliseconds"

date.exports.addMinutesToDate(date, n) ⇒ Date

Adds a certain number of minutes to a date object.

Kind: static method of date
Returns: Date - The date with minutes added.

Param Type Description
date Date | string The date to add minutes to.
n Number How many minutes to add to the date.

Example

_$.addMinutesToDate(new Date(), 4);//Create a date 4 minutes from now.

date.exports.isDateValid(...val) ⇒ Boolean

Validates a date from a string.

Kind: static method of date
Returns: Boolean - Returns if the date is valid or not.

Param Type Description
...val any The arguments of the date to validate.

Example

_$.isDateValid('December 17, 1995 03:24:00'); // true
    _$.isDateValid('1995-12-17T03:24:00'); // true
    _$.isDateValid('1995-12-17 T03:24:00'); // false
    _$.isDateValid('Duck'); // false
    _$.isDateValid(1995, 11, 17); // true
    _$.isDateValid(1995, 11, 17, 'Duck'); // false
    _$.isDateValid({}); // false

date.exports.addDaysToDate(date, n) ⇒ Date

Adds a specified number of days to a date.

Kind: static method of date
Returns: Date - The date with the specified number of days added.

Param Type Description
date Date The date to add days to
n Number How many days to add to the date.

element : object

The element namespace of Bijou.js, containing functions to create elements from query selectors, enable custom right click options, test if an element is on screen, replace the text of an element without altering it's styling, and much more!

Kind: global namespace

element.exports.ripple(el, obj) ⇒ HTMLElement

Applies a material design ripple effect to the element specified. Works best with buttons and similar elements. This comes from my GitHub repo here: https://github.com/explosion-scratch/ripple

Kind: static method of element
Returns: HTMLElement - The HTML element that the ripple effect was applied to. (The same one passed in the first param).

Param Type Default Description
el HTMLElement The element to apply the ripple effect to.
obj Object The object with (optional) time, color, opacity and event parameters for controlling the ripple effect. If these are not present the effect relies on data-* attributes, and then defaults and look good in general.
[obj.time] Number 1000 The time in milliseconds the ripple should take.
[obj.color] String "currentColor" The color of the ripple effect.
[obj.opacity] Number .3 The opacity of the ripple effect.
[obj.event] String "mousedown" The event to listen for to trigger the ripple effect.

Example

_$.each(document.querySelectorAll("button"), _$.ripple)
//Accepts attributes too!
// data-time: The time in milliseconds that it takes the ripple to fade away
// data-color: A CSS color that the ripple should have as it's color
// data-opacity: The starting opacity of the ripple effect.
// data-event: The event to listen for to apply the ripple.

element.exports.elementReady([parent], selector) ⇒ Promise

Waits for an element satisfying selector to exist, then resolves promise with the element.

Kind: static method of element
Returns: Promise - A promise resolved when the element exists.

Param Type Default Description
[parent] HTMLElement document.documentElement The parent element to watch.
selector String The querySelector to watch for.

Example

_$.elementReady("#text").then((e) => e.remove());//Wait for an element with an ID of "text" then removes it.

element.exports.elementContains(parent, child) ⇒ Boolean

Tests if an element is a child element of another element.

Kind: static method of element
Returns: Boolean - If the element is a child or not

Param Type Description
parent HTMLElement The parent element to test.
child HTMLElement The child element to test.

Example

_$.elementContains(document.querySelector("#container"), document.querySelector("#img"));//If the element with an id of "img" is inside the #container element this will return true, otherwise it will return false

Example

//Note that the easiest way to do this would be to use _$.onOutsideClick(), but this is another way that demonstrates the use of this function.
//Listen for a click outside of an element (in this case the div#popup element) then remove the popup element.
document.querySelector("div#popup").addEventListener("click", (e) => {
 let contains = _$.elementContains(document.querySelector("div#popup"), e.target);
 if (!contains){
   document.querySelector("div#popup".remove()
 }
})

element.exports.parents(el) ⇒ Array.<HTMLElement>

Gets the parent elements of the element given.

Kind: static method of element
Returns: Array.<HTMLElement> - An array of the parent elements from deepest to outermost.

Param Type Description
el HTMLElement The element

Example
//Where the html is like so:

<html>
 <head>
 </head>
 <body>
   <div id="img">
    <img src="https://example.com/example.png">
   </div>
 </body>
</html>

_$.parents(document.querySelector("img"));//[div#img, body, html]

element.exports.getImages([el], [includeDuplicates]) ⇒ Array

Gets all the images that are children of the specified element.

Kind: static method of element
Returns: Array - The array of image urls.

Param Type Default Description
[el] HTMLElement document.documentElement The element to get images from (e.g. document.body)
[includeDuplicates] Boolean false Whether to include duplicate images, defaults to false.

Example

//Get all the images on the page and convert their url's to data urls then log that list to console.
_$.getImages().forEach(image_url => {
 image_data_list.push(_$.imageToData(image_url))
})
console.log(image_data_list);

element.exports.renderElement(param, container) ⇒ HTMLElement

Renders an HTML element from an object in the container specified.

Kind: static method of element
Returns: HTMLElement - The HTML element rendered.

Param Type Description
param Object The type of object (the HTML tagName)
container HTMLElement The html element to render it in.

Example

//Renders a button in the document body.
_$.renderElement({
  type: 'button',
  props: {
    type: 'button',
    className: 'btn',
    onClick: () => alert('Clicked'),
    children: [{ props: { nodeValue: 'Click me' } }]
  }
}, document.body)

element.exports.create(querySelector, [content]) ⇒

Create a DOM element from a querySelector with option to include content

Kind: static method of element
Returns: DOMElement

Param Type Description
querySelector String (optional) default to div
[content] String | Number | DOMElement (optional)

Example

- _$.create(); // <div>
- _$.create('span#my-id.my-class.second-class'); // <span id="my-id" class="my-class second-class">
- _$.create('#my-id.my-class.second-class', 'text to insert', 12345); // <div id="my-id" class="my-class second-class">

element.exports.context() ⇒ Array.<HTMLElement>

Re-enables the use of <menu> and <menuitem> tags for corner clicking.

Kind: static method of element
Returns: Array.<HTMLElement> - An array of all the HTML elements passed.
Example
//HTML:

<h1 contextmenu="menu">Corner click me</h1>
<menu>
 <menuitem label="An item!">
 <menuitem label="Another item!">
</menu>

//JS _$.context(); // Now the user can corner click the items that have parents with a "contextmenu" attribute! Try it out here: https://bcs88.csb.app/

element.exports.inView(el) ⇒ Boolean

Tests whether the specified element is fully in view.

Kind: static method of element
Returns: Boolean - Whether the element is completely in view.

Param Type Description
el Element The DOM element to test.

Example

// Alerts "In view!" if the first <div> in the document is in view.
if (_$.inView(document.querySelector("div"))) alert("In view!");

element.exports.inPartialView(el) ⇒ Boolean

Tests if the given DOM element is partially (or fully) in view.

Kind: static method of element
Returns: Boolean - Whether the DOM element is partially in view.

Param Type Description
el Element The element to test.

Example

// Alerts "In view!" if the first <div> in the document is partially or fully view.
if (_$.inPartialView(document.querySelector("div"))) alert("In view!");

element.exports.replaceText(el, callback) ⇒ HTMLElement

Replaces the text in an element by running it through a callback.

Kind: static method of element
Returns: HTMLElement - The HTML element passed.

Param Type Description
el Element The element to replace the text of.
callback replaceTextCallback The callback to run (Gets passed the element's text).

Example

_$.replaceText(document.querySelector("div"), (text) => text.toUpperCase());
// Converts the text of the first <div> element to upperCase.

element.exports.textNodes(el) ⇒ Array

Gets a list of all the text nodes in an element

Kind: static method of element
Returns: Array - The text nodes.

Param Type Description
el Element The element to get the text nodes of.

Example

_$.textNodes(document.querySelector("h1"))[0].textContent = "hello world"; // replaces the text with "hello world" without deleting other elements

element.exports.querySelector(elem) ⇒ String

Generates a querySelector for an element passed in.

Kind: static method of element
Returns: String - The generated querySelector.

Param Type Description
elem Element The element to generate the querySelector for.

Example

const textarea = document.getElementById('textarea');
console.log(_$.querySelector(textarea)); //Logs "#textarea" to the console.

element.exports.removeComments(el) ⇒ HTMLElement

Removes comments from the element specified.

Kind: static method of element
Returns: HTMLElement - The HTML element with the comments removed.

Param Type Description
el Element The element to remove comments from.

Example

_$.removeComments(document.documentElement);//Removes the comments from the document element.

element.exports.parseHTML(string, [mimeType]) ⇒ HTMLDocument

Parses the string of HTML specified and returns an HTML element of it.

Kind: static method of element
Returns: HTMLDocument - The HTML document element of the HTML string specified.

Param Type Default Description
string String The HTML string to parse.
[mimeType] String "text/html" The mimeType of the string.

Example

let html = _$.parseHTML("<div id='hello'><textarea></textarea></div>");
html.querySelector("textarea");//Returns the textarea!

element.exports.drag(dragHandle, dragTarget) ⇒ Element

Allows an element to be dragged and dropped.

Kind: static method of element
Returns: Element - The element.

Param Type Description
dragHandle Element The element that when dragged should move the dragTarget.
dragTarget Element The element that should be moved when the dragHandle is dragged.

Example

_$.drag('div span', 'div'); // Allows the first <div> on the page to be dragged by the <span> element inside it.

element.exports.addEventListeners(element, events, handler, [useCapture], [args]) ⇒ Element

Adds multiple event listeners with one callback to the element specified.

Kind: static method of element
Returns: Element - The HTML element passed.

Param Type Default Description
element Element The element to add the event listeners to.
events Array.<String> The array of events to listen for.
handler eventListenersCallback The function to run when the events happen.
[useCapture] Boolean | Object false Whether to use capture, or an options object.
[args] Array false The arguments to use in the handler function.

Example

// Reset a timer every user interaction.
let timer = 0;
setInterval(() => timer++, 1);
_$.addEventListeners(
 document,
 ["mousemove", "click", "scroll", "keypress"],
 () => timer = 0,
);

element.exports.sortTable(element, [cellVal]) ⇒ HTMLTableElement

Kind: static method of element
Returns: HTMLTableElement - The table element. Sorts a table using JavaScript. This appends click listeners to every TH in the table.

) element, and the index of the cell.
Param Type Description
element HTMLTableElement The table to sort
[cellVal] sortTableCallback The callback function to run with the element to get the value of the cell. This is passed the cell () element, and the row (

Example

_$.sortTable(document.querySelector("table"));//Done.

Example

_$.sortTable(document.querySelector("table"), (i) => i.getAttribute("data-sort"));//Sorts the table by each cell's 'data-sort' attribute.

element.exports.sortTableBy(th, ascending) ⇒ HTMLTableElement

Sorts a table by a element.

Kind: static method of element
Returns: HTMLTableElement - The table element.

Param Type Description
th HTMLTableElement The table header ( element) to sort with.
ascending Boolean Whether to sort the table ascending or descending.

Example

//Note that this example pretty much recreates the _$ sortTable function, which is much more cross browser and good than this recreation. If sorting a whole table please use that.
_$.each(document.querySelectorAll("#table th"), (th) => {
 th.addEventListener("click", () => {
   //Add event listeners to each of them.
   _$.sortTableBy(th, th.asc = !th.asc);//Toggle the "asc" attribute on the th.
 });
})

element.exports.addStyles(el, styles) ⇒ Object

Adds the specified styles to the element specified.

Kind: static method of element
Returns: Object - the style object of the element.

Param Type Description
el Element The element to add the styles to.
styles Object An object that represents the styles to be added. (camelCased)

Example

_$.addStyles(document.documentElement, {backgroundColor: "#101010", color: "white"})

element.exports.createElement(str) ⇒ Element

Creates an HTML element from the specified string.

Kind: static method of element
Returns: Element - The created element.

Param Type Description
str String The string of the HTML element to create.

Example

//Returns a div with an id of "id_here" and innerText of "Testing!"
_$.createElement("<div id='id_here'>Testing!</div>");

element.exports.compStyle(el, prop) ⇒ String

Gets a property from the computed style of an element.

Kind: static method of element
Returns: String - The computed style property for the element specified.

Param Type Description
el Element The element whose styles to get.
prop String The css-property value to get of the styles.

Example

console.log(_$.compStyle(document.documentElement, "background-color")); // logs the background colour of the document

element.exports.elementSiblings(n) ⇒ Array.<Element>

Get the siblings of a DOM element

Kind: static method of element
Returns: Array.<Element> - The array of sibling elements.

Param Type Description
n Element The element to get siblings of

Example

_$.each(_$.elementSiblings(document.querySelectorAll("li")), (el) => el.style.backgroundColor = 'white');
// Make every sibling of the first list item's background color white.

element.exports.disableRightClick(el) ⇒ HTMLElement

Disables right click on the element specified.

Kind: static method of element
Returns: HTMLElement - The HTML element that now has right click disabled.

Param Type Description
el HTMLElement The element to disable right click on.

Example

_$.disableRightClick(document.documentElement)

element.exports.inlineCSS(el) ⇒ Object

Converts all of the styles for an element to inline CSS. This is nice for production sites because it means that they will look the same on all browsers. (Because it uses computed style.)

Kind: static method of element
Returns: Object - The computed styles of the element.

Param Type Description
el Element The element to convert.

Example

_$.inlineCSS(document.querySelector("h1")); // Converts the styles for the <h1> element to inline using the style="___" attribute

element.exports.attributes(el) ⇒ Array.<object>

Returns an array of objects representing the attributes of a passed element.

Kind: static method of element
Returns: Array.<object> - The array of objects representing the attributes

Param Type Description
el Element The HMTL element to get attributes from.

Example

// Say the <html> tag of the document was "<html style='background-color: #101010;'>", then the function below would log "style," to the console.
console.log(Object.keys(_$.attributes(document.documentElement).join(", "));

element.exports.observeMutations(element, callback, options) ⇒ MutationObserver

Observes the mutations of the html element specified.

Kind: static method of element
Returns: MutationObserver - The mutation observer.

Param Type Description
element Element The element to observe
callback function The callback function to run when a mutation happens.
options Object The options to use.

Example

_$.observeMutations(document, console.log); // Logs all the mutations that happen to the console.

element.exports.tilt(el, x, y, [perspective], [amount]) ⇒ String

Tilts a specified element to point towards the specified position. Note that 0,0 is the center of the screen in coordinates.

Kind: static method of element
Returns: String - The css transform string.

Param Type Default Description
el Element The element to tilt.
x Number The x value of the mouse
y Number The y value of the mouse
[perspective] Number 500 The perspective
[amount] Number 30 The amount to tilt.

Example

// Tilt the first image in the document whenever the mouse moves.
let el = document.querySelector("img");
el.onmousemove = (e) => {
 let x = e.layerX;
 let y = e.layerY
 _$.tilt(el, x, y);
}

element.exports.fullScreen(element) ⇒ Promise

Enters fullscreen on an element.

Kind: static method of element
Returns: Promise - A promise resolved when fullscreen is entered.

Param Type Description
element Element The element to enter full screen with.

Example

_$.fullScreen(document.documentElement); // Make the window fullscreen

element.exports.replaceSelection(replacementText) ⇒ Range

Replaces the selected text in a contentEditable div with the HTML given.

Kind: static method of element
Returns: Range - A range representing the users selection.

Param Type Description
replacementText String The replacement HTML to replace with.

Example

// Add a simple contenteditable div to the page.
document.appendChild(_$.createElement("<div contenteditable id='text'></div>"));
_$.replaceSelection("<b>BOLD TEXT</b> <small>Bijou is awesome</small><h1>You need to use it</h1>");
//Replaces the selection! =)

event : object

The event namespace of Bijou.js, containing functions to listen and dispatch events, such as scroll stop, outside click, and multiple event listeners.

Kind: global namespace

event.exports.waitUntil(condition, [wait]) ⇒ Promise

Waits until a condition is met then resolves a promise.

Kind: static method of event
Returns: Promise - A promise resolved when the condition returned by the function is true.

Param Type Default Description
condition function The function which returns true when the condition is met
[wait] Number Infinity The wait time in milliseconds to cancel the function and reject the promise.

Example

//Waits until the current second of the current minute is 10.
_$.waitUntil(() => new Date().getSeconds === 10).then(() => console.log("Done"))

Example

//This DOES NOT work
_$.waitUntil(() => Date.now() === Date.now() + 100);
//Because it is evaluated many times, and the current date, is never ahead of itself. Therefore in this case the function will run infinitely.
//To fix this problem and cancel the function after a certain amount of time,
//you can pass another argument to the function
_$.waitUntil(() => false, 10000);//Waits 10 seconds, because the function always returns false.

event.exports.onOutsideClick(element, callback) ⇒ Promise

Returns the callback when a a click is registered outside the selected element

Kind: static method of event
Returns: Promise - A promise that is resolved when the user clicks outside the specified element.

Param Type Description
element Element The element to use as the outsideclick element.
callback function The function to run when a click is registered outside the specified element.

Example

_$.onOutsideClick(document.querySelector("div"), () => {alert("You clicked outside the DIV!")});

event.exports.onScrollStop([element], callback, [time]) ⇒ Promise

Returns the callback when the user stops scrolling.

Kind: static method of event
Returns: Promise - Returns a promise that is resolved when the user stops scrolling.

Param Type Default Description
[element] HTMLElement window The HTML element to listen on for scroll stop.
callback function The callback to call when the user stops scrolling.
[time] Number 150

Example

_$.onScrollStop(() => {alert("You stopped scrolling!")})

event.exports.hub() ⇒ Object

A lot like socket.io, this allows emit, on and off handlers. (Note that this is local, only your computer sends and recieves your data. Still useful though)

Kind: static method of event
Returns: Object - The object with the emit, on and off functions in it.
Example

let thing = _$.hub();
// Log any new data to the console
thing.on("data", (data) => console.log(data));
setTimeout(() => {
  thing.emit("data", "Yay! Some data!!"); // Logs "Yay! Some data!!" to the console after 2 seconds.
}, 2000)

event.exports.dispatch(type, args, [target]) ⇒ Event

Dispatches an event of the type specified with custom arguments.

Kind: static method of event
Returns: Event - The event object.

Param Type Default Description
type String The type of event to dispatch (E.g. "mousemove")
args Object The argument representing the event, e.g. {clientX: 100, clientY: 150}
[target] EventTarget window What to dispatch the event to.

Example

//Dispatch a custom mouse move event to the window.
_$.dispatch("mousemove", {clientX: 100, clientY: 150, target: document.documentElement}, window);

function : object

The function namespace of Bijou.js, containing functions to work with functions themselves, such as debouncing, throttling, memoizing, currying, timing and much more!

Kind: global namespace

function.exports.juxt(...fns) ⇒ juxtCallback

Runs a list of functions with a list of arguments.

Kind: static method of function
Returns: juxtCallback - The function to run with the args.

Param Type Description
...fns function The functions to call.

Example

//It returns an array of outputs, each item in the base array is the output of one function, and each item in that array is the output for each argument.
_$.juxt(
    x => x + 1,
    x => x - 1,
    x => x * 10
  )(1, 2, 3); // [[2, 3, 4], [0, 1, 2], [10, 20, 30]]

function.exports.sleep(ms) ⇒ Promise

Returns a promise after a specified number of milliseconds.

Kind: static method of function

Param Type Description
ms Number The milliseconds to sleep.

Example

(async () => {
   while (true){
    document.body.innerHTML = (await _$.getJSON("https://time.jsontest.com")).time
    await _$.sleep(60000);//Wait one minute then loop.
   }
})

function.exports.limitArgs(fn, n) ⇒ function

Limits the arguments that a given function takes to only the 1st n arguments.

Kind: static method of function
Returns: function - The new function that only takes the 1st n arguments.

Param Type Description
fn function The function to call.
n Number The number of arguments to accept.

Example

//Now console can only log one item. How utterly useless but explanatory at the same time!
console.log = _$.limitArgs(console.log, 1);

function.exports.fastestFunction(fns, [iterations]) ⇒ Number

Returns the index of the fastest function in an array of functions.

Kind: static method of function
Returns: Number - The index of the fastest function in the array.

Param Type Default Description
fns Array.<function()> The array of functions to execute.
[iterations] Number 1000 How many times to execute the functions. (More is more reliable but takes longer.)

Example

_$.fastestFunction([_$.uuid, () => _$.syntaxHighlight("<h1>Hello world</h1>", "html")]);//0, the first function.

function.exports.spread(fn) ⇒ spreadCallback

Uses an array of arguments to make a function based on the one inputted.

Kind: static method of function

Param Type Description
fn function The function to use

Example

var say = _$.spread(function(who, what) {
    return who + ' says ' + what;
  });
  say(["Fred", "hi"]);//"Fred says hi"

function.exports.memoize(fn) ⇒ function

Memoizes a function, basically caching the result of past operations so that if the exact same thing is called again it will return the same value instantly.

Kind: static method of function
Returns: function - The memoized function.

Param Type Description
fn function The function to memoize.

Example

let uuid = _$.memoize(() => _$.uuid()); // uuid will always return the same uuid. (Note that _$.uuid is already very fast - it can generate up to 10 million values in 20 seconds.)

function.exports.composeFunction(...functions) ⇒ function

Composes two functions together. Read more here: https://www.codementor.io/@michelre/use-function-composition-in-javascript-gkmxos5mj

Kind: static method of function
Returns: function - The composed function.

Param Type Description
...functions function The functions to be composed.

Example

const add2 = (x) => x + 2;
const multiply2 = (x) => x * 2;
console.log(_$.composeFunction(add2, multiply2)(3)) // 8 - i.e  3 * 2 + 2

function.exports.curryFunction(fn, [arity]) ⇒ function

Returns the curried version of a function. Read more here: https://medium.com/@abitoprakash/implementing-a-curry-function-in-javascript-6a249dbcb1bb

Kind: static method of function
Returns: function - The curried version of the function.

Param Type Default Description
fn function The function to curry.
[arity] Number fn.length The arity (number of params) of the function to curry. {...*} [args] Optional arguments to pass to the function being curried.

Example

let fn = (x, y, z, w) => x * y * z * w;
console.log(_$.curryFunction(fn, 4, 5)(4)(3)(2)); // 120 i.e. 5 * 4 * 3 * 2

function.exports.isAsync(val) ⇒ Boolean

Returns if the given function is async or not.

Kind: static method of function
Returns: Boolean - True if the function is async and false if not.

Param Type Description
val function The function to test.

Example

const asyncFn = async (x) => x ** 3; // It's a silly function, but a good example
console.log(_$.isAsync(asyncFn)); // true

function.exports.timeFunction(fn, [name]) ⇒ Object

Times the function passed.

Kind: static method of function
Returns: Object - An object with "time" and "function" properties, time being time in milliseconds, and function being the original function passed.

Param Type Default Description
fn function The function to run and time.
[name] String _$ function timer The name of the timer

Example

// Times how long it took the user to enter their name.
_$.timeFunction(() => prompt("What's your name?"));

function.exports.throttle(func, options, wait) ⇒ function

Only runs the input function at MAX with the delay specified.

Kind: static method of function
Returns: function - The throttled function

Param Type Description
func function The function to run.
options Object.<Boolean> The options.
wait Number The number of milliseconds to wait.

Example

const alert_function = _$.throttle(() => {alert("hello")}, 5000)
setInterval(alert_function, 1)

function.exports.debounce(func, wait, [immediate]) ⇒ function

Debounces a function so that it only runs after it has not been called for a certain amount of time.

Kind: static method of function
Returns: function - The debounced function.

Param Type Default Description
func function The function to throttle.
wait Number The milliseconds to wait between executions.
[immediate] Boolean false Whether or not to run immediately, or after a group of executions.

Example

window.addEventListener("keyup", _$.debounce(expensiveFunction, 100));//Run the function expensiveFunction at most every 100ms.

function.exports.runAsync(fn) ⇒ Promise

Runs a function asynchronously in a web worker.

Kind: static method of function
Returns: Promise - A promise that resolves into the return value of the function.

Param Type Description
fn function The function to run

Example

_$.runAsync(() =>  "hello world").then(console.log); // "hello world"

math : object

The math namespace of Bijou.js, containing functions to validate credit card numbers, animate with JavaScript, generate unique id's and much more!

Kind: global namespace

math.ease : object

Easing functions

Kind: static namespace of math
Example

console.log(_$.ease.easeInOutQuad(.3)); // 0.18 - the eased point of about 1/3 along the animation.

math.exports.gcd(...arr) ⇒ Number

Gets the greatest common divisor of a list of numbers.

Kind: static method of math
Returns: Number - The greatest common divisor

Param Type Description
...arr Number The numbers to compare

Example

_$.gcd(12, 4, 8);//Returns 4

math.exports.round(number, amount) ⇒ Number

Rounds a number.

Kind: static method of math
Returns: Number - The rounded number

Param Type Description
number Number The number to round.
amount Number An optional multiple to round it to.

Example

console.log(_$.round(14, 10));//Logs 10 to the console, as 14 rounded to the nearest 10 is 10.

Example

console.log(_$.round(Math.PI));//Logs 3 to the console.

math.exports.equals(a, b)

Tests if two things are equal, like "thing === thing2" but it also works for dates and objects.

Kind: static method of math

Param Type Description
a * The first thing to test
b * The second thing to test

Example

console.assert(new Date() === new Date());//Not equal
console.assert(_$.equals(new Date(), new Date()));//Equal!

Example

console.assert({thing: "Thing!"} === {thing: "Thing!"});//Not equal;
console.assert(_$.equals({thing: "Thing!"}, {thing: "Thing!"}))

math.exports.isPrime(num) ⇒ boolean

Tests if a given number is prime.

Kind: static method of math
Returns: boolean - Whether the number is prime

Param Type Description
num Number The number to test.

Example

_$.isPrime(11);//True
_$.isPrime(10);//False

math.exports.factorial(n) ⇒ Number

Gets the factorial of a number given.

Kind: static method of math

Param Type Description
n Number The number to get the factorial of.

Example

_$.factorial(3);//6

math.exports.luhnCheck(num)

Performs the Luhn Check on a number, which is used to validate credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, Israeli ID Numbers, South African ID Numbers, Greek Social Security Numbers (ΑΜΚΑ), and survey codes appearing on McDonald's, Taco Bell, and Tractor Supply Co. receipts.

Kind: static method of math

Param Type Description
num Number | String The number or string to check on.

Example

- _$.luhnCheck('4485275742308327'); // true
    - _$.luhnCheck(6011329933655299); //  false
    - _$.luhnCheck(123456789); // false

math.exports.animate(start, end, duration, callback, [interval], [num]) ⇒ Number

Animates a number from one value to another.

Kind: static method of math
Returns: Number - A unique number representing the setInterval loop used in the animation.

Param Type Default Description
start Number The initial value of the number in the animation
end Number The final value of the number in the animation
duration Number The duration of the animation in milliseconds
callback animateCallback The callback function to run with the number and the percentage (Between 0 and 1) of the animation.
[interval] Number 20 The amount of time to wait between frames in milliseconds.
[num] animateNumCallback (num)=>num The function to run to manipulate the timing of the animation, for example setting this to (current_number) => current_number **2 would make a simple ease in function. (The value received by this is also between 0 and 1, feel free to use some stuff from _$.ease.FUNCTION_HERE(current_number) to incorporate easy easing!)

Example

Animates from 50 to 100 over the course of 3 seconds, updating every half second, and writing the current value to the document body.
_$.animate(50,100, 3000, (e) => document.body.innerHTML = (Math.round(e)), 500, (num) => _$.ease.easeInOutQuart(num));

math.exports.range(start, end) ⇒ Array.<Number>

Returns an array of the whole numbers (inclusive) between the numbers specified.

Kind: static method of math
Returns: Array.<Number> - An array of whole numbers (inclusive) between the numbers specified.

Param Type Description
start Number The start value of the array.
end Number The end value of the array.

Example

console.log(_$.range(-2, 1)); // [-2, -1, 0, 1]

math.exports.uuid([seed]) ⇒ String

Generates a unique ID from a seed

Kind: static method of math
Returns: String - The UUID

Param Type Default Description
[seed] Number | String Math.random() The seed to use.

Example

console.log(_$.uuid()); // e.g. "863d0193-863d-0193-863d-0193863d0193"

math.exports.primesTo(num) ⇒ Array.<Number>

Gives an array of prime numbers up to a certain one.

Kind: static method of math
Returns: Array.<Number> - Returns an array of prime numbers up to the given number.

Param Type Description
num Number The number to give primes to.

Example

console.log(_$.primesTo(10)); // [2, 3, 5, 7]

math.exports.random(min, max, [round], [seed]) ⇒ Number

Generates a random number between a minimum and maximum number

Kind: static method of math
Returns: Number - The random number generated.

Param Type Default Description
min Number The lowest number that the random value generated can be.
max Number The highest number that the random value generated can be.
[round] Boolean true Weather to round the generated number
[seed] Number Math.random() The seed for the generated number (Between 0 and 1).

Example

console.log(_$.random(0, 100)); // e.g. 47

math.exports.seedRandom(seed) ⇒ Number

Get a random number from a seed.

Kind: static method of math
Returns: Number - The random number from the seed.

Param Type Description
seed number The seed to use to generate random numbers.

Example

console.log(_$.seedRandom(13)); // 0.5663226493634284

math.exports.formatNumber(n) ⇒ String

Formats a number by adding commas to it.

Kind: static method of math
Returns: String - The formatted string representation of the number.

Param Type Description
n Number The number to format.

Example

console.log(_$.formatNumber(100000000)); // "100,000,000"

object : object

The object namespace of Bijou.js, for stuff like flattening nested objects, cloning, merging, and even listening to changes to objects!

Kind: global namespace

object.exports.flattenObj(o) ⇒ Object

Flattens an object recursively into one.

Kind: static method of object
Returns: Object - The flattened object.

Param Type Description
o Object The object to flatten

Example

_$.flattenObj({
	  hello: "world",
	  another: {
		  nested: "Value",
		  anotherNestedValue: {
			  "something": "A value"
		  },
		  "more Values!!": "lol"
	  }
  }); //  { hello: "world", nested: "Value", something: "A value", more Values!!: "lol" }

object.exports.clone(src) ⇒ Object

Deep clones an object (or anything else, like an array or string)

Kind: static method of object
Returns: Object - The output cloned object.

Param Type Description
src Object | Array | String The object to clone.

Example

let obj = { hello: { puny: "earthlings" }};
let cloned = _$.clone(obj); // cloned can be operated on without changing obj

object.exports.listen(obj, [getCallback], [setCallback]) ⇒ Proxy

Kind: static method of object
Returns: Proxy - A proxy object that behaves like any other object but listens to changes.

Param Type Default Description
obj Object The object to listen to.
[getCallback] listenCallback ()=>null The callback function to run when a value is set, with the arguments, key (the key changed) and value (the new value of the key).
[setCallback] listenCallback ()=>null The callback function to run when a value is gotten, with the arguments, key (the key got) and value (the value of the key).

Example

let obj = {something: "This is part of the object", anotherThing: "This is another!"};
obj = _$.listen(obj, (k, v) => console.log(`set ${k} to ${v}`), () => console.log("Gotten"));
obj.something; // Logs "Gotten" to the console!
obj.anotherThing = "Hello world!"; // Logs "Set abotherThing to Hello world!" to the console!

object.exports.merge(obj1, obj2) ⇒ Object

Merges two objects into one. Note that object 2 properties will overwrite those of object 2.

Kind: static method of object
Returns: Object - The merged object.

Param Type Description
obj1 Object The 1st object to merge
obj2 Object The 2nd object to merge.

Example

console.log(_$.merge({hello: "Hello!!"}, {world: " World", world: " Earthlings"})); // {hello: "Hello!!", world: " Earthlings"}

object.exports.mapObjectKeys(obj, fn) ⇒ Object

Maps the keys of an object.

Kind: static method of object
Returns: Object - The new Object.

Param Type Description
obj Object The object to map.
fn mapObjKeysCallback The function to run (passed the current key of the object) which returns the new value from that key.

Example

_$.mapObjectKeys({something: "A value", anotherThing: "Another value!"}, (key) => key.toUpperCase());
//Returns {SOMETHING: "A value", ANOTHERTHING: "Another value!"}

object.exports.mapObjectValues(obj, fn) ⇒ Object

Maps an object's values.

Kind: static method of object
Returns: Object - The mapped object.

Param Type Description
obj Object The object to map the values of.
fn mapObjValuesCallback The callback function to use.

Example

console.log(_$.mapObjectValues({ hello: "World", bijou: "is GREAT" }, val => val.toLowerCase())); // { hello: "world", bijou: "is great" }

object.exports.formToObject(form) ⇒ Object

Converts a form to an Object.

Kind: static method of object
Returns: Object - The object of form data (The keys are the "name" attributes of the form inputs and the values are the value attributes of the form data.)

Param Type Description
form HTMLFormElement The form element.

Example
html:

<form id="form">
  <input name"input" />
  <input name="input2" />
</form>

js: const form = document.getElementById("form"); console.log(_$.formToObject(form)); // e.g. { input: "hello", input2: "world" }

object.exports.sortObj(obj) ⇒ Object

Sorts an object alphabetically by its keys.

Kind: static method of object
Returns: Object - The sorted object.

Param Type Description
obj Object The object to sort.

Example

let object = _$.sortObj({testing: "A value", anotherThing: "Another value!"});
// The object is now {anotherThing: "Another value!", testing: "A value"}

object.exports.deepGet(key, object) ⇒ *

Retrieves a deeply nested value from an object given a key.

Kind: static method of object
Returns: * - The retrieved value or null if the key does not exist.

Param Type Description
key string | Array.<string> The key (if string will split by '.') or an array of keys to access the value.
object object The object to retrieve the value from.

Example

_$.deepGet("hello.world", {hello: {world: "Hello World!"}}); // "Hello World!"

object.deepSet(path, value, obj) ⇒ Object

A function that sets a value at a given path in an object by creating nested objects along the way for any undefined keys in the path, while keeping the original object immutable.

Kind: static method of object
Returns: Object - A new object with the updated value at the given path

Param Type Description
path string | Array.<string> The path to set the value at, can be either a string or an array of strings
value any The value to set at the given path
obj Object The object to set the value in

Example

const obj = { a: { b: { c: 1 } } };
const newObj = deepSet("a.b.d", 2, obj);

console.log(newObj);
// Output: { a: { b: { c: 1, d: 2 } } } }

string : object

The string namespace of Bijou.js, containing functions to map strings, remove accents from strings, speak text, syntax highlight JS, HTML and CSS and much more!

Kind: global namespace

string.exports.jaroDistance(a, b) ⇒ Number

Compares two strings using the Jaro-Winkler Distance algorithm.

Kind: static method of string
Returns: Number - A number representing how similar the two strings are, where 1 is exactly the same and 0 is totally different

Param Type Description
a String The first string
b String The second string

Example

_$.jaroDistance('test', 'tes');//0.9416666666666667

string.exports.prefixCSS(prop) ⇒ String

Prefixes the given CSS property for the current browser.

Kind: static method of string
Returns: String - The prefixed value (camelCased, instead of css-case, so mozAppearance instead of -moz-appearance).

Param Type Description
prop String The property to prefix.

Example

document.body.style[_$.prefix("appearance")] = "hidden";//Sets the document body's appearance property to "hidden".

string.exports.parseCookie(str)

Parses a cookie string into object and value pairs.

Kind: static method of string

Param Type Description
str String The string to parse.

Example

_$.parseCookie("foo=bar; something=hello%20world");//Returns {foo: "bar", something: "hello world"};

string.exports.hash(val) ⇒ Promise

Hashes a string using the crypto api.

Kind: static method of string
Returns: Promise - A promise that resolves into the hashed string.

Param Type Description
val String The string to hash

Example

_$.hash(
	JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })
  ).then(console.log);
  // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'

string.exports.forTemplateLiteral(arr, callback) ⇒ String

Lets you use a for loop in template literals.

Kind: static method of string
Returns: String - String that has been for looped

Param Type Description
arr Array The array to loop.
callback mapCallback The callback to return strings

Example

console.log(`Things: ${_$.forTemplateLiteral(["apple", "orange"], (item, i) => {return `an ${item}`})}`)
// "Things: an apple an orange

string.exports.mapString(str, fn)

Maps a string like an array.

Kind: static method of string

Param Type Description
str String The string to map
fn mapCallback The callback function to run to map the string.

Example

_$.mapString("Hello world", (e) => e.toUpperCase());//Returns "HELLO WORLD"

string.exports.deburr(str) ⇒ String

Removes the accents from a string.

Kind: static method of string
Returns: String - The string without accents.

Param Type Description
str String The string to use.

Example

console.log(_$.decurr("déjà vu")); // "deja vu"

string.exports.removeTags(html) ⇒ String

Removes tags from the HTML string specified.

Kind: static method of string
Returns: String - THe string of HTML without the tags.

Param Type Description
html String The string of HTML to remove tags from.

Example

console.log(_$.removeTags("<div>Hello</div>")); // "Hello"

string.exports.speak(text, [lang], [volume], [voice], [pitch], [volume], [rate]) ⇒ SpeechSynthesisUtterance

Speaks the text given.

Kind: static method of string
Returns: SpeechSynthesisUtterance - The SpeechSynthesisUtterance

Param Type Default Description
text String The text to split
[lang] String en-US The language to speak with.
[volume] Number 1 The volume
[voice] String | Number 1 The voice to use.
[pitch] Number 1 The pitch
[volume] Number 1 The volume
[rate] Number 1 The speed.

Example

_$.speak("Bijou is awesome!"); // speaks "Bijou is awesome!"

string.exports.widows(text) ⇒ String

Returns the last space in the string given replaced with " "

Kind: static method of string
Returns: String - The replaced string.

Param Type Description
text String The string to replace

Example

document.querySelector("h1").innerHTML = _$.widows(document.querySelector("h1").innerHTML);
//Replaces the last space in the <h1>'s innerText with "&nbsp;"

string.exports.unCamelCase(str) ⇒ String

Undoes camelCase.

Kind: static method of string
Returns: String - The string of unCamelCased code.

Param Type Description
str String The string to unCamelCase.

Example

console.log(_$.unCamelCase("helloWorld")); // "Hello World"

string.exports.camelCase(str) ⇒ String

camelCases a string.

Kind: static method of string
Returns: String - The camelCased string.

Param Type Description
str String The string of non-camelCased text.

Example

console.log(_$.camelCase("Hello world")); // "helloWorld"

string.exports.scrambleString(str) ⇒ String

Scrambles the order of characters in a string. Thanks to @\Touchcreator for the suggestion for this.

Kind: static method of string
Returns: String - The scrambled text.

Param Type Description
str String The string to be scrambled

Example

console.log(_$.scrambleString("Hello world")); // e.g. "owllH rdloe"

string.exports.hashString(str, [seed]) ⇒ Number

Hashes a string to a unique integer (This cannot be decrypted easily).

Kind: static method of string
Returns: Number - The hashed string.

Param Type Default Description
str String The String to hash.
[seed] Number 0 The seed of the hash.

Example

console.log(_$.hashString("Hello world")); // 3494146707865688

string.exports.editDistance(a, b) ⇒ Number

Gets the edit distance between two strings.

Kind: static method of string
Returns: Number - The edit distance between two strings

Param Type Description
a String The first string
b String The seconds string

Example

console.log(_$.editDistance("hello", "Hello")); // 1

string.exports.byteSize(str) ⇒ Number

Returns the size of a string in bytes.

Kind: static method of string
Returns: Number - The byte size of the string.

Param Type
str String

Example

console.log(_$.byteSize("Hello world")); 11

string.exports.replaceMultiple(text, replace) ⇒ String

Finds and replace multiple values with multiple other values.

Kind: static method of string
Returns: String - The replaced string

Param Type Description
text String The text to operate the replace on.
replace Object The object with find and replace values.

Example

_$.replaceMultiple("I have a cat, a dog, and a goat.", {dog: "cat", goat: "dog", cat: "goat"});//Returns "I have a goat, a cat and a dog"

string.exports.urlQuery(query, [url]) ⇒ String

Returns the queries from a given url (Or just the current url)

Kind: static method of string
Returns: String - The url query

Param Type Default Description
query String The url query to get.
[url] String window.location.href The url to find the query in. (By default this is the current url)

Example

// If the website adress of the current page was "https://example.com/?q=hello&hello=world"
console.log(_$.urlQuery("hello")); // "world"
// Or on a custom url:
console.log(_$.urlQuery("q", "https://google.com/search?q=something")); // "something"

string.exports.sanitize(html, [tags], [attributes]) ⇒ String

Sanitizes an HTML string. It is quite possible that this is not production ready so use with caution. (I did my best though >=( )

Kind: static method of string
Returns: String - The sanitized HTML string.

Param Type Description
html String The input string to sanitize.
[tags] Array The array of tags to allow, there is a default list though.
[attributes] Array The array of attributes to allow. By default only allows "href" and "src" attributes.

Example

console.log(_$.sanitizeHTML("<script>alert('hello')></script><b>A normal tag</b>")); // "<b>A normal tag</b>"

string.exports.markdownToHTML(src) ⇒ String

Converts markdown to HTML.

Kind: static method of string
Returns: String - The string of HTML converted from the markdown input.

Param Type Description
src String The markdown to convert to HTML.

Example

console.log(_$.markdownToHTML("_Italic text_, **bold text**")); // "<em>Italic text</em>, <b>bold text</b>"

string.exports.syllables(word) ⇒ Number

Counts the syllables in the word given.

Kind: static method of string
Returns: Number - The number of syllables in the specified word.

Param Type Description
word String The word to count syllables of

Example

console.log(_$.syllables("Hello")); // 2

string.exports.titleCase(str) ⇒ String

Converts a string to title case

Kind: static method of string
Returns: String - The string in title case.

Param Type Description
str String The string to convert to title case.

Example

_$.titleCase("hello world");//Returns "Hello World"

string.exports.capitalize(str) ⇒ String

Capitalizes the first letter of the string

Kind: static method of string
Returns: String - The capitalized string.

Param Type Description
str String The string to capitalize.

Example

console.log(_$.capitalize("hello world")); // "Hello world"

string.exports.replaceBetween(string, start, end, what) ⇒ String

Replaces between two indexes of a string.

Kind: static method of string
Returns: String - The replaced string

Param Type Description
string String The string to operate on.
start Number The start index
end Number The end index
what String What to replace with.

Example

console.log(_$.replaceBetween("Hello world", 6, 11, "earthlings")); // "Hello earthlings"

string.exports.escapeHTML(str) ⇒ String

Escapes a string of HTML

Kind: static method of string
Returns: String - The escaped HTML.

Param Type Description
str String The string of HTML to escape.

Example

console.log(_$.escapeHTML("<div>")); // "&lt;div&gt;"

string.exports.unescapeHTML(str) ⇒ String

Unescapes a string of HTML

Kind: static method of string
Returns: String - The unescaped HTML.

Param Type Description
str String The string of HTML to unescape.

Example

console.log(_$.unescapeHTML("&lt;div&gt;")); // "<div>"

string.exports.previousPage() ⇒ String

Returns the previous page that the user visited.

Kind: static method of string
Returns: String - The url of the previous page the user visited.
Example

console.log(_$.previousPage()); // e.g. "https://bijou.js.org"

string.exports.processList(list) ⇒ Array

Processes a markdown list by extracting the content of each list item and returning an array of objects with the content and its index in the list.

Kind: static method of string
Returns: Array - - An array of objects with the content and its index in the list

Param Type Description
list string the list to be processed

Example

const list = '- Item 1\n- Item 2\n- Item 3';
const processedList = processList(list);

// Returns:
// [
//   { content: 'Item 1', idx: 0 },
//   { content: 'Item 2', idx: 1 },
//   { content: 'Item 3', idx: 2 }
// ]

utility : object

The utility namespace of Bijou.js, containing utilities to do many things, such as playing audio, fetching JSON, preloading images and much more.

Kind: global namespace

utility.exports.createStream ⇒ MediaStream

Creates a MediaStream with all of the tracks passed.

Kind: static property of utility
Returns: MediaStream - A MediaStream object which has all of the tracks passed.

Param Type Description
...tracks MediaStreamTrack A list of the tracks to add to the new media stream.

Example

//Combine video from screen share with audio from microphone
const audioStream = await navigator.mediaDevices.getUserMedia({audio: true});
//Get the audio track, streams can have more than one track.
const audioTrack = audioStream.getAudioTracks()[0];

//Do the same for video (get from screen share)
const videoStream = await navigator.mediaDevices.getDisplayMedia({video: true});
const videoTrack = videoStream.getVideoTracks()[0];

//   Now use the _$.createStream function to create a new stream with the
// audio from the microphone and the video from the screen share.
const combinedStream = createStream(audioStream, videoStream);//Order doesn't matter, _$.createStream also accepts an array of streams.

utility.exports.manipulate ⇒ Promise.<MediaStreamTrack>

Kind: static property of utility
Returns: Promise.<MediaStreamTrack> - Returns a promise that resolves into a mediaStream with the original videoStream but manipulated by whatever the fn function returns (see example).

Param Type Description
videoTrack MediaStreamTrack A video track to manipulate
fn manipulateVideoStreamFunction The function given to manipulate the video stream.

Example

//Greenscreen effect
let video = document.createElement("video");
video.setAttribute("autoplay", true);
document.body.appendChild(video);

//Now the cool part
let videotrack = await navigator.mediaDevices.getUserMedia({video: true})
		.then(stream => stream.getVideoTracks()[0]);

//    Basically manipulate the video track using canvas, and for every color,
// if its green value is above 200 then make that pixel transparent.
// Creating a simple greenscreen effect.
video.srcObject = _$.createStream(
_$.manipulate(videotrack, (color) => {
		if (color.green > 200){
			//Simple greenscreen effect
			color.alpha = 0;
		}
		return color;
	})
)

utility.exports.tag ⇒ function

Creates a template literal tag. Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates

Kind: static property of utility
Returns: function - A template literal tagging function, which returns a string.

Param Type Description
k function The function to run on new (interpolated) text in the template literal.
o function The function to run on the normal text in the template literal.

Example

let t = tag(_$.escapeHTML);
//Notice the "t" at the beginning of the template literal. (t`Some text`).
console.log(t`This will not be escaped <i>Italics!</i> ${"But this will, <i>Not italic</i>"}`)

utility.exports.request ⇒ Object | Response | String | Image

Request a URL and get the data back in a specific format.

Kind: static property of utility

Param Type Default Description
options Object The options object
options.url String The URL to fetch
options.body Object | String | FormData The body of the request
[options.as] String | Array.<String> "response" What to fetch the data as. A string that is one of ["response", "blob", "json", "dataurl", "text", "image", "html", "bloburl", "headers"], or an Array of multiple. If an array (e.g. ["text", "json"]) an object with {text: "{'some': 'json'}", json: {some: "json"}} will be returned
[options.method] String "GET" One of ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"]
[options.options] Object {} An options object that is passed to fetch(url, options).
[options.headers] Object {} Headers object to add to the request before sent
[options.type] Object | String "json" The type of the request payload. One of ["JSON", "urlencoded", "text", "formdata"] (not case sensitive). For urlencoded or JSON, pass an object as options.body, for text, pass a string, for formdata pass a FormData object, and for raw, pass anything. This is then added into fetch(url, {body: body})
[options.corsFallback] Boolean true Whether to retry the request via a cors proxy if it fails
[options.corsDomain] String 'https://cors.explosionscratc.repl.co/&#x27; The cors domain to use as a proxy
[options.detectCors] function ({response, error}) => error
[options.makeCorsUrl] function (url, domain) => `${domain}${url.split("//")[1]}` The function which takes a URL and domain as an input and returns the altered URL to be retried with CORS. For example makeCors("https://google.com", "https://cors.explosionscratc.repl.co/") would return "https://cors.explosionscratc.repl.co/google.com"
[options.timeout] Number The timeout (in ms) before cancelling the request. If null than there will be no timeout handling.

Example

let response = await _$.request({
	url: "https://google.com",
	as: ["html", "bloburl"],
	timeout: 1000
})
// → {html: #document, bloburl: "blob:https://github.com/abc-def-ghi"}

utility.preload : object

preload links when hovering over them, to have no-refresh page navigation

Kind: static namespace of utility

utility.cookies ⇒ function

A set of functions to set and modify cookies.

Kind: static namespace of utility
Returns: function - The function that the user wanted
Example

_$.cookies.setItem("a_cookie", "Hello world!", 1); // Set a_cookie to "Hello world" and have it expire in a day.

utility.regex ⇒ Regexp

A collection of regular expressions to validate and get common things from a page

Kind: static namespace of utility
Returns: Regexp - A regex
Example

if (_$.regex.email.test("email@gmail.com") alert("That is a valid email!")

utility.exports.resize(url, [width], [height]) ⇒ Promise.<string>

Resizes an image from a URL and returns a promise with it's data URL.

Kind: static method of utility
Returns: Promise.<string> - A data URL of the resized image.

Param Type Default Description
url String The URL of the image to resize.
[width] Number Natural width of the image The target width of the new image
[height] Number Natural width of the image The target height of the new image

utility.exports.htmlToImage(html, [opts]) ⇒ Promise.<string>

Converts a string of HTML to an image (!!)

Kind: static method of utility
Returns: Promise.<string> - A promise that resolves into the data URL string of the image.

Param Type Default Description
html String The HTML string to transform into an image
[opts] Object.<string> {x: 0, y: 0, width: 300, height: 400} The object with options.
[opts.x] Number 0 The x position of the text
[opts.y] Number 0 The y position of the text
[opts.width] Number 300 The width of the output image.
[opts.height] Number 400 The height of the output image.

utility.callbackify(fn) ⇒ function

Converts a function that returns a promise into a callback based function

Kind: static method of utility
Returns: function - The callback based function.

Param Type Description
fn function The function to 'callbackify'.

Example

let getUUID = _$.callbackify((limit) =>
   fetch(
       `https://apis.explosionscratc.repl.co/uuid?limit=1${escape(parseInt(limit))}`
   ).then(res => res.json()));

getUUID(console.log, 500);//Get 500 uuid's from my API and log them to the console.

utility.promisify(fn, [argIndex]) ⇒ function

Promisifies a function by converting a callback based function to return a promise. (assuming argIndex = -1)

Kind: static method of utility
Returns: function - The function promisified (now returns a promise).

Param Type Default Description
fn function The function to run.
[argIndex] Number 0 The index of the argument that is the callback returned by the function.

Example

let time = _$.promisify(setTimeout);
(async () => {
	await time(2000);
	console.log("It's been 2 seconds.")
})();

utility.exports.race(fn, timeout, calcelCb) ⇒ Promise

Times out a promise after a specified number of milliseconds.

Kind: static method of utility
Returns: Promise - The promise that was inputted, but will time out after a specified time.

Param Type Description
fn function The function to run that should return a promise, or the promise itself.
timeout Number The timeout to cancel after.
calcelCb function The callback to run when cancelled, defaults to throwing an error.

Example

//Attempts to fetch the date from jsontest.com, if the request is still pending after 2000 milliseconds cancel it and throw an error.
let fetch_stuff = fetch("http://date.jsontest.com/");
_$.race(fetch_stuff, 2000).then((res) => res.json()).then(console.log).catch(console.error)

Example

//Load my popup library, then prompt using it and after 4 seconds close and remove the popup.
(async () => {
 //Load the script, but check for duplicates! ;)
	await _$.loadScript("https://cdn.jsdelivr.net/gh/explosion-scratch/popup/popup.js", {}, true);
	_$.race(prompt("Enter something in the next 4 seconds!"), 4000).then(console.log).catch(() => {
		document.querySelector("#popup").remove();
		document.querySelector("#popup-bg").remove();
		console.log("User could not type fast enough -__-")
	})
});

utility.exports.typeOf(e, lowerCase)

Gets the type of something. This is more specific than the 'typeof' operator.

Kind: static method of utility

Param Type Description
e * The thing to get the type of.
lowerCase Boolean Whether to return the string lowercased or not.

Example

_$.typeof("This is a string");//"String"
typeof "This is a string";//Also string

Example

_$.typeof(/^[regex]$/i);//"RegExp".
typeof /^[regex]$/i;//"object"

Example

_$.typeof(new Date());//"Date"
typeof new Date();//Object -__-

utility.exports.injectCSS(css) ⇒ HTMLElement

Injects CSS into the document head.

Kind: static method of utility
Returns: HTMLElement - The CSS <style> element.

Param Type Description
css String The CSS to inject.

Example

//Makes the body's background a dark charcoal color.
_$.injectCSS("body {background: #101010; color: white;}");

Example

//Set the text color to an appropriate color depending on the background color of the document body:
if (_$.lightOrDark(_$.compStyle(document.body, "background-color")).lightOrDark === "light"){
   _$.injectCSS(`
     body {
       color: ${_$.lightenColor(_$.rgbToHex(_$.compStyle(document.body, "background-color")), -100)};
     }
   `)
} else {
   _$.injectCSS(`
     body {
       color: ${_$.lightenColor(_$.rgbToHex(_$.compStyle(document.body, "background-color")), 100)};
     }
   `)
}

utility.exports.mobileOrDesktop() ⇒ String

Returns either "mobile" or "desktop" depending on which type of device the user is using.

Kind: static method of utility
Returns: String - Either "mobile" or "desktop" depending on which type of device the user is using.

| | | |

Example

console.log(_$.mobileOrDesktop()); // e.g. "desktop"

utility.exports.playSection(audioObj, start, stop) ⇒ Audio

Plays a section of an audio file.

Kind: static method of utility
Returns: Audio - The audio object first passed.

Param Type Description
audioObj HTMLMediaElement The audio object to play. (Needs to be created from "new Audio()")
start Number The time to start playing.
stop Number The time to stop playing.

Example

_$.playSection(new Audio("file.mp3"), 5, 20.5); // Plays file.mp3, starting with second 5 and ending at 20.5 seconds into the file.

utility.exports.formatHTML(html) ⇒ String

Formats a string of HTML using indents. Note that this does not format CSS or JS in the HTML.

Kind: static method of utility
Returns: String - The formatted string of HTML.

Param Type Description
html String The string of HTML to format.

Example
console.log(_$.formatHTML("

moo

hello world
")); Logs the following to the console:

   <h1>moo</h1>
   <div id='hi'>hello <span>world</span>
   </div>

utility.exports.getJSON(url, callback) ⇒ Promise

Gets JSON from a URL and performs a callback with it.

Kind: static method of utility
Returns: Promise - A promise resolved when the JSON is fetched and parsed.

Param Type Description
url String The url of the JSON to be fetched.
callback function The function to be run with the JSON code.

Example

_$.getJSON("http://date.jsontest.com/", (json) => {alert("The current time is " + json.time)})

utility.exports.getHTML(url, callback) ⇒ Promise

Gets HTML from a URL and performs a callback with it.

Kind: static method of utility
Returns: Promise - A promise resolved when the HTML is fetched and parsed.

Param Type Description
url String The url of the HTML to be fetched.
callback function The function to be run with the HTML code.

Example

// Logs the HTML of wikipedia.org to the console.
_$.getHTML("https://wikipedia.org", (html) => console.log(html));

utility.exports.preloadImage(...urls) ⇒ Array.<Image>

Preloads all of the image urls given in the arguments

Kind: static method of utility
Returns: Array.<Image> - An array of all the Image elements created to preload.

Param Type Description
...urls String The urls of the images to be preloaded.

Example

_$.preloadImage("https://unsplash.com/some_huge_image.png"); // Preloads the unsplash image "some_huge_image.png" :P

utility.exports.saveBlob(blob, [fileName]) ⇒ Blob

Saves a blob as a file!

Kind: static method of utility
Returns: Blob - The blob saved.

Param Type Default Description
blob Blob The blob to save as a file.
[fileName] String output.txt The name of the output file (Must include the extension.)

Example

_$.saveBlob(new Blob(["Yay! I'm in a text file!"]), "Cool file.txt");

utility.exports.requestInterval(fn, delay) ⇒ Object

Works exactly like setInterval but instead uses requestAnimationFrame.

Kind: static method of utility

Param Type Description
fn function The function to run repeatedly every delay seconds.
delay Number The delay time in milliseconds to run the function.

utility.exports.loadScript(url, callback) ⇒ Promise

Loads a script from a url (Can be to a local file or to a url) then runs a callback once it's loaded.

Kind: static method of utility
Returns: Promise - A promise resolved once the script is loaded.

Param Type Description
url String The url to load the script from.
callback function The callback to run when the script is loaded.

Example

_$.("script.js", ()=>alert("Script loaded!"));//Loads the script from the "script.js" file

utility.exports.imageToData(url, callback) ⇒ Promise

Fetches an image and runs the callback with the data url of the image.

Kind: static method of utility
Returns: Promise - A promise fulfulled when the image is loaded.

Param Type Description
url String The url of the image to load.
callback function The callback function.

Example

//Replaces every image's url with its respective data url.
_$.each(document.querySelectorAll('img'), (img) => {
  _$.imageToData(img.src, (data) => {
   img.src = data;
 })
})

utility.exports.jsonToCsv(arr, columns, [delimiter]) ⇒ String

Converts JSON to a CSV string

Kind: static method of utility
Returns: String - The string of comma separated values (CSV) created from the JSON.

Param Type Default Description
arr Array The array of objects to convert to CSV.
columns Array The columns to use.
[delimiter] String "," The delimiter between cells, by default this is a comma.

Example

_$.jsonToCsv(
    [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],
    ['a', 'b']
  );
//
   a,b
  "1","2"
  "3","4"
  "6",""
  "","7"

utility.exports.arrayToCSV(arr, [delimiter]) ⇒ String

Converts an array to CSV (Comma separated values) data.

Kind: static method of utility
Returns: String - The comma separated array.

Param Type Default Description
arr Array The array to convert.
[delimiter] String , The separator (By default this is a comma.)

Example

console.log(_$.arrayToCSV([1,2,3,4])); // "1,2,3,4"

utility.exports.notify(title, body, icon) ⇒ Promise

Displays a desktop notification with the specified text.

Kind: static method of utility
Returns: Promise - A promise that fulfills once the notification is sent, and is rejected when there is an error

Param Type Description
title String The title of the notification.
body String The body of the notification.
icon String The url to the image for the icon of the notification.

Example

_$.notify("Hello", "Hi there! This is a notification!"); Notifies the user with the title "Hello" and the body text "Hi there! This is a notification!"

utility.exports.copy(str) ⇒ String

Copies the string inputted to the clipboard.

Kind: static method of utility
Returns: String - The string copied.

Param Type Description
str String The string to copy.

Example

_$.copy("Hello world");

utility.exports.browser() ⇒ String

Returns the browser that the user is using.

Kind: static method of utility
Returns: String - A string of the browser name that the user is using.
Example

_$.browser(); // For me this (correctly) returns "Chrome"

utility.exports.serializeForm(form) ⇒ String

Converts a form to URL queries using the name attribute.

Kind: static method of utility
Returns: String - The string of url queries (Excluding the hostname and path) of the form data.

Param Type Description
form HTMLFormElement The form element.

utility.exports.soundex(s) ⇒ String

An implementation of the soundex algorithm in JavaScript, used to test if two words sound the same.

Kind: static method of utility
Returns: String - The soundex of the given string

Param Type Description
s String The word to get the soundex of.

Example

_$.soundex("ekxplohsin");//"E214"
_$.soundex("explosion");//"E214"

node()

Tests if the user is using Node.js or not and throws an error in specific functions (that require the DOM) if they are.

Kind: global function

averageByFn ⇒ Number

Kind: global typedef
Returns: Number - The number to average

Param Type Description
number Number The number to perform the operation on

eachCallback : function

Kind: global typedef

Param Type Description
x any The item of the array/string/number range
i Number The index of the item in the array/string/number range
array Array.<any> The original array

replaceTextCallback ⇒ String

Kind: global typedef
Returns: String - The replaced text

Param Type Description
text String The text to replace

eventListenersCallback ⇒ undefined

Kind: global typedef

Param Type Description
e Event The event object

sortTableCallback ⇒ String

Kind: global typedef
Returns: String - The cell content

Param Type Description
td HTMLTableCellElement The td element
tr HTMLTableRowElement The tr element
cellIndex Number The cell index

scrollStopCallback ⇒ undefined

Kind: global typedef

Param Type Description
event UIEvent The event object

juxtCallback ⇒ Array.<array>

Kind: global typedef
Returns: Array.<array> - The list of outputs.

Param Type Description
...args any The arguments to run on the functions

spreadCallback ⇒ any

Kind: global typedef

Param Type Description
args Array The array of arguments

listenCallback ⇒ undefined

Kind: global typedef

Param Type Description
key String | Symbol The key being accessed
value any The value of the key being accessed

mapObjKeysCallback ⇒ String

Kind: global typedef

Param Type Description
key String The key

mapObjValuesCallback ⇒ any

Kind: global typedef

Param Type Description
value any The value

animateNumCallback ⇒ Number

Kind: global typedef

Param Type
num Number

animateCallback ⇒ undefined

Kind: global typedef

Param Type
num Number
percent Number

mapCallback : function

Kind: global typedef

Param Type Description
item any The item
i Number The index of the item
arr Array The original array

manipulateVideoStreamFunction ⇒ Object

Kind: global typedef
Returns: Object - Returns an object with red, green, blue and alpha keys.

Param Type Description
pixel Object
pixel.red Number The red value of the pixel (0-255)
pixel.green Number The green value of the pixel (0-255)
pixel.blue Number The blue value of the pixel (0-255)
pixel.alpha Number The alpha value of the pixel (0-255)

Example

//Example function given to _$.manipulate
(color) => {
	if (color.green > 200){
		//Simple greenscreen effect
		color.alpha = 0;
	}
	return color;
}