gorilla.js π¦ - the only javascript utility library π¦ you'll ever need.
Minified 6.41 KB πͺ; Minified and Gzipped only 2.6 KB bytes π₯!
jQuery 3.0.0-alpha1 is 85 KB π’; Minified and Gzipped still a whopping π 29 KB π.
Don't be sad, we got you IE >= 9 users covered β€.
(Even if this means supporting 7 years old software π€·)
There's a gorilla.compat.min.js
version, which even works in IE9 ππ»!
- gorilla.after
- gorilla.ajax
- gorilla.append
- gorilla.attr
- gorilla.before
- gorilla.copyToClipboard
- gorilla.compareJSON
- gorilla.css
- gorilla.create
- gorilla.data
- gorilla.DOMReady
- gorilla.find
- gorilla.getImageData
- gorilla.getParsedURL
- gorilla.getRandomNumer
- gorilla.getURLParams
- gorilla.getUnixtime
- gorilla.height
- gorilla.html
- gorilla.inArray
- gorilla.loadCSS
- gorilla.loadJS
- gorilla.log
- gorilla.on
- gorilla.one
- gorilla.prepend
- gorilla.remove
- gorilla.serialize
- gorilla.stringEndsWith
- gorilla.stringFormat
- gorilla.waitForElementToBePresent
- gorilla.width
Wrapper for appending elements after
some element.
var newListElement = gorilla.create("li")
.attr("style", "color:red;").html("New List Element");
// Appends a new list element after the 3rd li found in the DOM
gorilla.find("li").get(2).after(newListElement);
Simple ajax request wrapper which returns a promise.
gorilla.ajax({
url: "pokemon/pokedex.json",
method: "POST",
cache: true,
requestContentType: "application/x-www-form-urlencoded",
headers: {
"X-Gorilla-Custom-Header": "This is really awesome!",
"X-Gorilla-Custom-Header2": "Gorilla Fam for life!",
"X-Gorilla-Style": "Best style in the universe!"
},
params: {
format: "json",
query: "all"
}
})
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
Consecutive ajax requests made easy and without callback hell:
// first, load pokemon items
gorilla.ajax({ url: "pokemon/items.json" })
.then((pokemonItems) => {
console.log(JSON.parse(pokemonItems));
// after pokemon items have been loaded, load pokemon skills
return gorilla.ajax({ url: "pokemon/skills.json" });
})
.catch((errPokemonItems) => {
// loading pokemon items failed
console.log(errPokemonItems);
})
.then((pokemonSkills) => {
console.log(JSON.parse(pokemonSkills));
// after pokemon skills have been loaded, load pokemon types
return gorilla.ajax({ url: "pokemon/types.json" });
})
.catch((errPokemonSkills) => {
// loading pokemon skills failed
console.log(errPokemonSkills);
})
.then((pokemonTypes) => {
// these are the pokemon types
console.log(JSON.parse(pokemonTypes));
})
.catch((errPokemonTypes) => {
// loading pokemon types failed
console.log(errPokemonTypes);
});
Wrapper for appendChild
.
var newListElement = gorilla.create("li")
.attr("style", "color:red;").html("New List Element");
gorilla.find("ul").get(0).append(newListElement);
Wrapper for setAttribute
and getAttribute
.
// retrieve `href` value of first link
gorilla.find("a").get(0).attr("href")
// set href value of first link
gorilla.find("a").get(0).attr("href", "#foo");
Set multiple values at once:
gorilla.find("a").get(0).attr({
"href": "test.html",
"data-foo": "baz",
"data-bar": "foo"
});
Wrapper for insertBefore
.
var newFirstListElement = gorilla.create("li").html("First List Element");
// Insert `newFirstListElement` before the first `li` found.
gorilla.find("li").get(0).before(newFirstListElement);
Copies text to the clipboard.
let text = "This is some awesome text.";
gorilla.copyToClipboard(text);
Compares to JSON structures and returns either true
if they are identical
in terms of properties, or false
if they don't have each others properties.
var json1 = {
foo: true,
moo: false
};
var json2 = {
foo: true,
moo: false
};
var json3 = {
foo: true,
moo: true
};
var json4 = {
foo: false,
moo: false
};
// This should return true, because they are seen as "equal"
console.log(gorilla.compareJSON(json1, json2);
// This should return false, because they lack have the same
// properties, but not the same values for each property
console.log(gorilla.compareJSON(json3, json4);
Gets the getComputedStyle
for an element.
Also can set CSS styles (<div style="color:red;border:1px solid black;">
).
When used as a setter, it returns the element itself. When used as a getter, it returns the values.
Get specific CSS style:
gorilla.css(el, "color");
// or
gorilla.find("li").get(0).css("color");
Get all CSS styles:
gorilla.css(el);
// or
gorilla.find("li").get(0).css();
Get specific CSS styles:
gorilla.css(el, ["color", "border"]);
// or
gorilla.find("li").get(0).css(["color", "border"]);
Set CSS styles:
gorilla.css(el, {
color: "#f00",
border: "1px solid #000"
});
// or
gorilla.find("li").get(0).css({
color: "#f00",
border: "1px solid #000"
});
Returns the element.
Wrapper for document.createElement
.
gorilla.create("input")
.attr("type", "text")
.attr("placeholder", "E-Mail");
Helper for setting and getting data-
attributes.
Returns the element.
Set one data-
attribute (set data-autosuggest
to string true
):
gorilla.create("input")
.data("autosuggest", "true");
Returns the element.
gorilla.create("input")
.data({
autosuggest: true,
timeout: false
keynav: true
});
Returns a string or null.
Get data-
value (get the value for data-autosuggest
):
gorilla.find("input").get(0).data("autosuggest");
Returns JSON.
gorilla.find("input").get(0).data([
"autosuggest",
"timeout"
]);
The output would look something like this:
{
"autosuggest": "true",
"timeout": "25000"
}
Simple DOMReady wrapper.
gorilla.DOMReady(function() {
alert("dom is ready!");
});
Advanced querySelectorAll
with attaching convenience methods to elements.
This method always returns an array of objects and you either need to use the
get
method or the find("selector")[3]
element by index method to get the
element.
gorilla.find("ul").get(0)
.find("li").get(2)
.find("a").get(0)
.on("click", function(evt) {
evt.preventDefault();
alert("click");
});
Returns a JSON including width and height of the requested image.
gorilla.getImageData("https://gorilla.moe/favicon.ico")
.then((res) => console.log(res))
.catch((err) => console.log(err))
Returns a parsed URL object.
gorilla.getParsedURL("https://cdn.gorilla.moe/conor-mcgregor-song.mp4?gorilla=moe#hashicorp");
Returns
{
"hash": "#hashicorp",
"host": "cdn.gorilla.moe",
"hostname": "cdn.gorilla.moe",
"href": "cdn.gorilla.moe",
"pathname": "/conor-mcgregor-song.mp4",
"port": undefined,
"protocol": "https",
"search": "?gorilla=moe"
}
Returns a random number.
gorilla.getRandomNumber();
var min = -200; // if omitted, defaults to 0
var max = 200; // if omitted, defaults to Number.MAX_SAFE_INTEGER
gorilla.getRandomNumber(min, max);
Returns the current UNIX-Timestamp.
console.log(gorilla.getUnixtime());
Returns a URL params object.
console.log(gorilla.getURLParams("index.php?param1=value1¶m2=value2"));
Should return;
{
"param1": "value1",
"param2": "value2"
}
Setter and getter for (DOM-)element height.
Usage:
gorilla.height(el); // get the height of el
gorilla.find("ul").get(0).height(); // get the height of the first <ul> tag.
Set the height (numbers only - translated to px):
gorilla.height(el, 200); // set height of el to 200px
// this translates to el.style.height = '200px';
// set the height of the first <ul> tag to 200px
gorilla.find("ul").get(0).height(200);
Wrapper for innerHTML
.
gorilla.find("a").get(0).html("This is a Hyperlink.");
Utility function. Checks for existence of needle
in array
.
gorilla.inArray(array, needle);
// returns true
gorilla.inArray([1, 2, 3], 1);
// returns true
gorilla.inArray([1, 2, 3], 3);
// returns true
gorilla.inArray([1, 2, 3], 2);
// returns false
gorilla.inArray([1, 2, 3], 4);
Easy to use CSS file loader.
Creates a <link rel="stylesheet" href="">
tag and returns a promise.
gorilla.loadCSS("https://cdn.sstatic.net/Shared/stacks.css")
.then((el) => {
// link tag
console.log(el);
})
.catch((err) => {
console.log(err);
});
or multiple files, one by one..
gorilla.loadCSS("https://cdn.sstatic.net/Shared/stacks.css")
.then((el) => {
console.log(el);
return gorilla.loadCSS("https://cdn.sstatic.net/Sites/stackoverflow/primary-unified.css");
})
.catch((err) => console.log(err))
.then((el) => {
console.log(el);
})
.catch((err) => console.log(err));
Easy to use JavaScript file loader.
Create a <script>
tag and returns a promise.
gorilla.loadJS("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/core.js")
.then((el) => {
// script tag
console.log(el);
})
.catch((err) => {
console.log(err);
});
or multiple files, one by one..
gorilla.loadJS("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/core.js")
.then((el) => {
console.log(el);
return gorilla.loadJS("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js");
})
.catch((err) => console.log(err))
.then((el) => {
console.log(el);
})
.catch((err) => console.log(err));
Sexy wrapper around console.log
, console.warn
, console.debug
and
console.error
.
// defaults to info (green)
gorilla.log()("Hello there.", "hai", 1, true, {foo: true, bar: 'baz'});
// explicitly call info (green)
gorilla.log("info")("Hello there.", "hai", 1, true, {foo: true, bar: 'baz'});
// warn (yellow)
gorilla.log("warn")("Hello there.", "hai", 1, true, {foo: true, bar: 'baz'});
// error (red)
gorilla.log("error")("Hello there.", "hai", 1, true, {foo: true, bar: 'baz'});
// debug (blue)
gorilla.log("debug")("Hello there.", "hai", 1, true, {foo: true, bar: 'baz'});
Simple wrapper for addEventListener.
Each element that was returned by gorilla.find
has a method on
attached to
it.
gorilla.find("a").get(0).on(function(evt) {
evt.preventDefault();
alert("click");
});
Advanced querySelector
with attached convenience methods on the element.
This method returns an element or null
.
const anchor = gorilla.one("a");
if (anchor) {
gorilla.one("a").on(function(evt) {
evt.preventDefault();
alert("click");
});
}
Wrapper for insertBefore
.
var newFirstListElement = gorilla.create("li").html("First List Element");
// Insert `newFirstListElement` before the first `li` found.
gorilla.find("li").get(0).prepend(newFirstListElement);
Removes a node and all its children.
// Removes the first li tag found
gorilla.find("li").get(0).remove();
Encode a set of form elements (or JSON/JavaScript Object) as a string for submission.
Serialize Form-data:
gorilla.serialize(gorilla.find("form").get(0));
Serialze JSON:
gorilla.serialize({
id: 1,
name: "Gorilla Moe",
title: "Blogpost #1",
content: "Awesome content goes here..",
tags: {
0: "javascript",
1: "golang",
2: "php",
3: {
0: "foo",
1: "bar",
2: "baz"
}
}
});
// Returns
// id=1&name=Gorilla%20Moe&title=Blogpost%20%231&content=Awesome%20content%20goes%20here..&tags[0]=javascript&tags[1]=golang&tags[2]=php&tags[3][0]=foo&tags[3][1]=bar&tags[3][2]=baz
Returns true if the haystack
string ends with the needle
string.
Usage:
// Returns true
gorilla.stringEndsWith("This haystack ends with", "with");
// Returns false
gorilla.stringEndsWith("This haystack ends with foo", "with");
Formats a string.
Usage:
gorilla.stringFormat("I have %i apples and I really %s them.", 1337, "hate");
Or with more human friendly variables (because everything is a string π)
gorilla.stringFormat("I have %count dogs and I really %mood them.", 3, "adore");
Waits for DOM-Element to become present (/available).
The default interval (opts.interval=200
) it checks for the existence
of the element is 200ms.
The default timeout (opts.timeout=5000
) it errors out (return cb(err, null)
)
when the element is not found is 5000ms.
If opts.timeout
is set to Number.Infinity
it will keep checking for the
element indefinitely.
Usage:
// wait for element with id foobar to become ready
gorilla.waitForElementToBePresent("#foobar", (err, res) => {
if (err) return console.log(err);
console.log(res);
});
// append div#foobar after 2.5 seconds to the body tag
setTimeout(() => {
document.body.appendChild(gorilla.create("div").attr("id","foobar"));
},2500);
Check every 200ms for element to become available, for a total of 10 seconds; then fail.
// wait for element with id foobar to become ready
gorilla.waitForElementToBePresent("#foobar", (err, res) => {
if (err) return console.log(err);
console.log(res);
}, {
timeout: 10000,
interval: 200
});
Setter and getter for (DOM-)element width.
Usage:
gorilla.width(el); // get the width of el
gorilla.find("ul").get(0).width(); // get the width of the first <ul> tag.
Set the width (numbers only - translated to px):
gorilla.width(el, 200); // set width of el to 200px
// this translates to el.style.width = '200px';
// set the width of the first <ul> tag to 200px
gorilla.find("ul").get(0).width(200);
Icon (free for commercial use) made by Martin Berube.