Overview
Bliss includes several static methods (on the Bliss
or $
object). For example, to copy all properties of an object onto another object, you would call $.extend()
:
var yolo = $.extend({foo: 1}, {bar: 2}); // or Bliss.extend(…)
// yolo is {foo: 1, bar: 2}
Many of Bliss’ methods take an element or an array of elements as their first argument. For example, to set both the width
and padding
of an element to 0, you could use the $.style()
method:
$.style(element, {width: 0, padding: 0});
These types of methods are also available on elements and arrays, for convenience. However, since adding convenience methods to elements and arrays directly would be a JS Mortal Sin™, Bliss only adds a _
property on elements & arrays, on which it hangs all its methods, to avoid conflicts. The previous example would be written as:
element._.style({
"width": 0,
"padding": 0
});
Methods that are available on elements like this will have an Element tag in these docs.
If you wanted to set the width and padding of multiple elements to 0, you could use an array:
myArray._.style({
"width": 0,
"padding": 0
});
Methods that are available on arrays like this will have an Array tag in these docs.
For example, assume that in addition to these CSS changes you also wanted to add a hidden
attribute to this element. Bliss methods that don’t return a value return the element or array they are called on, so you could call more element methods on them, including native ones:
element._.style({
"width": 0,
"padding": 0
}).setAttribute("hidden", "");
Now assume you also wanted to set a second attribute: The "class" attribute to "foo". The native setAttribute()
method is not chainable, it returns undefined
. However, all native element methods are also available on the almighty _
property, and there they are also chainable:
element._.style({
"width": 0,
"padding": 0
})._.setAttribute("hidden", "").setAttribute("class", "foo");
This works, but it’s a bit unwieldy. Thankfully, Bliss offers an $.attributes()
method for setting multiple attributes at once:
element._.style({
"width": 0,
"padding": 0
})._.attributes({
"hidden": "",
"class": "foo"
});
This is better and more readable, but still a bit awkward. Turns out there is a special $.set()
method to do both at once:
element._.set({
attributes: {
"hidden": "",
"class": "foo"
},
style: {
"width": 0,
"padding": 0
}
});
Because $.attributes()
and $.style()
are also available for $.set()
parameters, they will have the special $.set() tag in these docs.
Note that you don’t actually need attributes: {…}
in $.set()
at all: if there are any unrecognized properties in the parameter object, Bliss will first check if there is a property with that name on the element and if not, set an attribute. So you could rewrite the example above as:
element._.set({
"hidden": "",
"class": "foo", // or "className": "foo" to use the property
style: {
"width": 0,
"padding": 0
}
});
DOM
Note: The $
is just an alias to Bliss
. If another library that uses $
is included before Bliss, then Bliss will not use $
. You can always alias $
to Bliss
manually, by putting this before any of your code (but after including Bliss):
self.$ = Bliss;
Similarly, $$()
is an alias to Bliss’ $.$()
or Bliss.$()
function. If it’s already defined by the time Bliss is called, Bliss will not use it. You can do so manually with this line:
self.$$ = Bliss.$;
When writing Bliss plugins, if you want to use $()
and $$()
it’s good practice to make local variables with them, in case they’re not available:
(function($, $$){
// Plugin code here
})(Bliss, Bliss.$)
Select an element by selector. Mainly a shortcut for element.querySelector()
.
var element = $(selector [, context])
- selector
- The CSS selector to use.
- context
- Returned element needs to be a descendant of this element.
:scope
inside selector
refers to this element (for supporting browsers).
- element
- The matched element or
null
if none found.
// return the first element with a class of .foo
// that is inside the first element with a class of .bar
var ret = $(".foo", $(".bar"));
// Return the first element with a class of .foo
// that is inside any element with a class of .bar
var ret = $(".bar .foo");
// Get the first element with a class of .foo
// and set its title attribute to "yolo"
// If there is no such element, this will throw an exception!
$(".foo").setAttribute("title", "yolo");
- If the element is not found, it will return
null
. This could cause an exception if methods are called on the result.
You might previously check if the element exists by caching the node in a variable
into an if
statement:
// Check if the .foo element exists
// and set an attribute by using a variable "foo"
// as a reference of the element
var foo = $(".foo");
if (foo) {
foo.setAttribute("title", "yolo");
}
$
Get all elements that match a given selector as an array. Similar to element.querySelectorAll()
but returns an Array instead of a NodeList, so it has all of the convenience methods we’ve come to love on arrays.
var array = $$(selector [, context])
- selector
- The CSS selector to use.
- context
- Returned elements need to be a descendants of this element.
:scope
inside selector
refers to this element (for supporting browsers).
- array
- The matched elements as an array.
var array = $$(collection)
- collection
- Type: Array-like
- Any array-like object, such as a NodeList, a function’s
arguments
object or an elements element.attributes
collection.
- array
- The collection converted to an array.
// Add an id to all <h1> headings that don’t already have one
$$("h1:not([id])").forEach(function(h1){
h1.id = h1.textContent.replace(/\W/g, "");
});
// Get an array with all ids on the page
var ids = $$("[id]").map(function(element){
return element.id;
});
// Get all of an element’s attributes starting with data-bliss-
$$(element.attributes).filter(function(attribute){
return attribute.name.indexOf("data-bliss-") === 0;
}).map(function(attribute){
return attribute.name;
});
create
Create an element.
var element = $.create([tag,] [options]);
- tag
- The tag name of the element to create.
- options
- An object with several options for the new element (properties, attributes, events etc). For details about what options this object accepts, see
$.set()
. If tag
is omitted, you need to provide it in the options
object.
- element
- The newly created element.
$.create("ul", {
className: "nav",
contents: [
"Navigation: ",
{tag: "li",
contents: {tag: "a",
href: "index.html",
textContent: "Home"
}
},
{tag: "li",
contents: {tag: "a",
href: "contact.html",
textContent: "Contact",
target: "_blank"
}}
]
});
var paragraph = $.create("p");
var div = $.create();
set
Set multiple traits of an element (properties, attributes, events, contents etc). One of the most useful functions in Bliss.
subject = $.set(subject, options);
subject = subject._.set(options);
- subject
- The element to apply the options on.
- options
- An object with various options, including:
- *
- Any remaining properties will be added as properties or attributes on the element (Bliss first checks if there is a property with that name, and if not, it sets it as an attribute.
$.set(document.createElement("nav"), {
style: {
color: "red"
},
events: {
click: function(evt) {
console.log("YOLO");
}
},
contents: ["Navigation: ", {tag: "ul",
className: "buttons",
delegate: {
click: {
li: function() {
console.log("A list item was clicked");
}
}
},
contents: [{tag: "li",
contents: {tag: "a",
href: "index.html",
textContent: "Home"
}
}, {tag: "li",
contents: {tag: "a",
href: "docs.html",
textContent: "Docs"
}
}
]
}],
inside: $("body > header")
});
- Tip: Add more specially handled properties of your own by just adding a function to
$.setProps
.
- Warning: If setting SVG attributes, use the explicit
attributes
property, not just properties directly on options
. Otherwise, they will be added as properties, and the API for SVG DOM properties is the stuff of nightmares.
contents
Append existing or newly created element(s) and text nodes to an element.
subject = $.contents(subject, elements)
subject = subject._.contents(elements)
subject = subject._.set({contents: elements})
- subject
- The element(s) to append the elements to.
- elements
- If it’s an object, it will be passed through
$.create()
, to be converted into an element. If it’s a string or number, it will be converted to a text node. If it’s a Node
it will be used as-is. If it’s an array, its elements will be processed according to the aforementioned rules. Note that this lets you recursively create entire subtrees, since these objects can also have a contents
property of their own, as seen in the example below.
nav._.contents(["Navigation: ", {tag: "ul",
className: "buttons",
delegate: {
click: {
li: function() {
console.log("A list item was clicked")
}
}
},
contents: [{tag: "li",
contents: {tag: "a",
href: "index.html",
textContent: "Home"
}
}, {tag: "li",
contents: {tag: "a",
href: "docs.html",
textContent: "Docs"
}
}
]
}])
jQuery.fn.html
clone
Clone an element including its descendants, with events and data. This function is deprecated and will be removed in the next version of Bliss
var clone = $.clone(subject)
var clone = subject._.clone()
- subject
- The element to be cloned.
- clone
- The cloned element.
var button = $("button");
button.addEventListener("click", function() { console.log("Click from listener!"); });
button.onclick = function() { console.log("Click from inline event!"); };
var button2 = button._.clone();
// If clicked, button2 will print both messages
jQuery.fn.clone
after
Insert an element after another.
subject = $.after(subject, element)
subject = subject._.after(element)
subject = subject._.set({after: element})
- subject
- The element to be inserted.
- element
- The element to insert after.
jQuery.fn.after
around
Wrap an element around another.
subject = $.around(subject, element)
subject = subject._.around(element)
subject = subject._.set({around: element})
- subject
- The element to wrap with.
- element
- The element to be wrapped.
// Wrap headings with a link to their section
$$("section[id] > h1, article[id] > h1").forEach(function(h1){
$.create("a", {
href: "#" + h1.parentNode.id,
around: h1
});
});
jQuery.fn.wrap
attributes
Set multiple attributes on one or more elements.
subject = $.attributes(subject, attrs)
subject = subject._.attributes(attrs)
subject = subject._.set({attributes: attrs})
- subject
- The element(s) to set the attributes on.
- attrs
- An object with the attributes and values to set.
- If only setting one attribute on one element, consider using the native
element.setAttribute(name, value)
. If setting one attribute on multiple elements, you can use myArray._.setAttribute(name, value)
.
toggleAttribute
Set or remove an attribute based on a test
subject = $.toggleAttribute(subject, name, value [, test])
subject = subject._.toggleAttribute(attrs)
- subject
- The element(s) to set the attributes on.
- name
- The attribute name
- value
- The attribute value
- test
- The test. If truthy, set the attribute. If falsy, remove it. If not present, it’s false when
value
is null
and true otherwise.
before
Insert the element before another.
subject = $.before(subject, element)
subject = subject._.before(element)
subject = subject._.set({before: element})
- subject
- The element to be inserted.
- element
- The element to insert before.
jQuery.fn.before
inside
Insert the element inside another, after any existing contents.
subject = $.inside(subject, element)
subject = subject._.inside(element)
subject = subject._.set({inside: element})
Mainly useful inside $.set()
, otherwise just use the native element.appendChild(subject)
.
jQuery.fn.append
properties
Set a number of properties on an element.
subject = $.properties(subject, props)
subject = subject._.properties(props)
subject = subject._.set({properties: props})
- subject
- The element(s) to set the properties on.
- props
- The properties to set on the element.
document.createElement("button")._.properties({
className: "continue",
textContent: "Next Step",
onclick: function() { MyApp.next() }
});
- If only setting one property on one element, just use
element[property] = value;
. If setting multiple properties on one element, you can use $.extend(subject, props)
instead.
jQuery.fn.prop
start
Insert an element inside another, before its existing contents.
subject = $.start(subject, element)
subject = subject._.start(element)
subject = subject._.set({start: element})
jQuery.fn.prepend
style
Set multiple CSS properties on one or more elements. Both camelCase and hyphen-case attributes are allowed.
subject = $.style(subject, properties)
subject = subject._.style(properties)
subject = subject._.set({style: properties})
- subject
- The element(s) to apply the CSS properties to.
- properties
- The CSS properties to apply, in camelCase format
document.body._.style({
color: "white",
backgroundColor: "red",
cssFloat: "left",
"--my-variable": 5
});
- If only setting one property on one element, you don’t need this. Just use the native
element.style.propertyName = value;
syntax.
jQuery.fn.css
transition
Set multiple CSS properties with a transition and execute code after the transition is finished.
var promise = $.transition(subject, properties [, duration])
var promise = subject._.transition(properties [, duration])
- subject
- The element(s) to apply the transitions to.
- properties
- The CSS properties to apply, in camelCase format
- duration
- The duration, in milliseconds. Defaults to 400.
- promise
- Promise that gets resolved after the transition is done, or immediately if CSS transitions are not supported.
// Fade out an element then remove it from the DOM
$.transition(element, {opacity: 0}).then($.remove);
// Fade out and shrink all <div>s on a page,
// then remove them from the DOM
Promise.all($$("div")._.transition({
opacity: 0,
transform: "scale(0)"
})).then($.remove);
- Uses CSS transitions, not custom interpolation code. In browsers that do not support CSS transitions, the style is applied immediately and the promise returned is resolved.
- The properties applied remain after the transition has ended.
jQuery.fn.animate
Events
delegate
Helper for event delegation. Helps you register events for children at an ancestor, so that when you add children that match the provided selector, they also trigger the event.
subject = $.delegate(subject, type, selector, callback)
subject = subject._.delegate(type, selector, callback)
- subject
- The delegation root. Only elements inside this will fire the event.
- type
- The event type.
- selector
- The selector the target of the event needs to match.
subject = $.delegate(subject, type, selectorsToCallbacks)
subject = subject._.delegate(type, selectorsToCallbacks)
- subject
- The delegation root. Only elements inside this will fire the event.
- type
- The event type.
- selectorsToCallbacks
- An object of the form
{selector1: callback1, …, selectorN: callbackN}
.
subject = $.delegate(subject, typesToSelectorsToCallbacks)
subject = subject._.delegate(typesToSelectorsToCallbacks)
subject = subject._.set({delegate: typesToSelectorsToCallbacks})
- subject
- The delegation root. Only elements inside this will fire the event.
- typesToSelectorsToCallbacks
- An object of the form
{
type1: {selector11: callback11, …, selector1N: callback1N},
…
typeM: {selectorM1: callbackM1, …, selectorMK: callbackMK}
}
.
jQuery.fn.delegate
bind
Set multiple event listeners on one or more elements.
subject = $.bind(subject, handlers)
subject = subject._.bind(handlers)
- subject
- The element(s) to set the event listeners on.
- handlers
- An object whose keys are the events and the values the listeners.
For details on the keys, see
types
below.
For details on the values, see callback
and options
below.
$$('input[type="range"]')._.bind({
"input change": function(evt) { this.title = this.value},
"focus.className": function(evt) { console.log(evt.type); }
})
subject = $.bind(subject, types, [callback], [options])
subject = subject._.bind(types, [callback], [options])
- subject
- The element(s) to set the event listeners on.
- types
- The event type. You can include multiple event types by space-separating them.
You can add a “class” on each event type by using a period (
click.myclass
), which you can later use in $.unbind()
for unbinding all events with a certain class at once.
- callback
- The function to execute. Passed directly to
addEventListener
.
- options
- Capture or options object to pass to
addEventListener
.
For details on what options are available, refer to the documentation for addEventListener
You can also combine the options
and callback
parameters, by including a callback
property.
This is useful when using the syntax above for multiple handlers if you also want to pass options.
- If only setting one event listener on one element and you are keeping a reference to the callback (or are using Bliss Full), just use the native
element.addEventListener(type, handler, useCapture)
syntax.
- You can use classes in your event names, like
click.foo
. The event that will be bound in that case is without the class name (click
), but you can use the class name to unbind via $.unbind()
jQuery.fn.bind
events
Just like $.bind()
, but also lets you copy events from another element.
The latter is the only syntax described here, for the $.bind()
syntax look above.
subject = $.events(subject, element)
subject = subject._.events(element)
subject = subject = subject._.set({events: element})
- subject
- The element(s) to set the event listeners on.
- element
- The element to copy listeners from. Inline events set via HTML or
on*
properties are also copied.
- If using Bliss Shy, only listeners added via Bliss methods will be copied.
unbind
Unbind event listeners en masse.
subject = $.unbind(subject, handlers)
subject = subject._.unbind(handlers)
- subject
- The element(s) to unbind the event listeners from.
- handlers
- An object whose keys are the event types and the values the callbacks.
For details about what these can be, read about the
type
and callback
arguments below.
$$('input[type="range"]')._.unbind({
"input change": function(evt) { this.title = this.value},
})
subject = $.unbind(subject, [type[, callback]])
subject = subject._.unbind([type[, callback]])
- subject
- The element(s) to unbind the event listeners from.
- type
- The event type. You can include multiple event types by space-separating them.
If using Bliss Full:
You can also unbind by class (e.g.
click.foo
or even just .foo
to unbind all events with that class).
You can also unbind all listeners on the element, by not providing any arguments. This will remove all listeners with capture option set to either true or false.
This works for Bliss Shy and anonymous functions too, if the listeners were added using Bliss bind method. Bliss (both Full and Shy) keeps track of anonymous functions so these listeners may be removed later.
- callback
- The callback. If using Bliss Full, this is optional. If not provided, all callbacks matching the event type and/or class specified by
type
will be unbound.
document.body._.events({
"click.foo mousedown.foo": function(e) { console.log("foo", e.type)},
"click.bar mousedown.bar": function(e) { console.log("bar", e.type)},
});
// Clicking on the body now prints foo mousedown, bar mousedown, foo click, bar click
document.body._.unbind(".foo");
// Clicking on the body now prints bar mousedown, bar click
document.body._.unbind("click");
// Clicking on the body now prints only bar mousedown
document.body._.unbind(); // unbind ALL events
// Clicking on the body now does nothing
$.unbind(elem)
// Removing all listeners from elem, regardless of event capture setting.
// If using Bliss Shy, $.unbind only works for the listeners added using $.bind method
$.unbind(elem, '', false)
// Removing all listeners from elem, with capture option set to false (the default in most browsers)
$.unbind(elem, '', true)
// Removing all listeners from elem, with capture option set to true explicitly
- If only unbinding one event listener and you have a reference to the callback used, just use the native
element.removeEventListener(type, handler, useCapture)
syntax.
- If using Bliss Shy, only listeners bound via Bliss methods can be removed without a reference to the callback.
- Avoid using overly liberal unbinding queries (e.g. no arguments or just a type) in code meant to be used in environments you don’t control.
You don’t want to conflict with other people’s code! Use a class instead.
jQuery.fn.unbind
fire
Fire a synthesized event.
subject = $.fire(subject, type [, properties])
subject = subject._.fire(type [, properties])
- subject
- The element(s) to fire the synthesized event on.
- type
- The event type.
- properties
- If provided, these properties will be added to the event object.
// Fire a custom event on a map widget
myMap._.fire("locationchange", {
location: [42.361667, -71.092751]
});
// Fire a fake input event
myInput._.fire("input");
- If you are writing a library meant to be run on websites you don’t control, it is recommended that you namespace your events by adding the library name before them, like
"mylibrary-locationchange"
or "mylibrary:locationchange"
, to avoid collisions.
jQuery.fn.trigger
once
Set event listeners that will be fired once per callback per element.
subject = $.once(subject, handlers)
subject = subject._.once(handlers)
subject = subject = subject._.set({once: handlers})
- subject
- The element(s) to set the event listeners on.
- handlers
- An object whose keys are the events and the values the listeners. You can include multiple event types by space-separating them.
jQuery.fn.one
ready
Execute code after the DOM is ready.
var promise = $.ready([context], [callback])
- context
- The document whose …readiness we’re interested in.
- callback
- A callback that gets executed synchronously if the DOM is already ready or on
DOMContentLoaded
if not.
- promise
- A promise that gets resolved immediately if the DOM is already ready, or on
DOMContentLoaded
if not.
// Add a red border to all divs on a page
$.ready().then(function(){
$$("div")._.style({ border: "1px solid red" });
});
jQuery.fn.ready
when
Defer code until an event fires.
var promise = $.when(subject, type [, test])
var promise = subject._.when(type [, test])
- subject
- The element to listen for the event on.
- type
- The event type.
- test
- If provided, this test will also need to pass for the promise to resolve.
- promise
- A promise that gets resolved once BOTH the event is fired and the test (if one is present) passes.
// Defer code until Esc is pressed for the first time
$.when(document, "keyup", evt => evt.key === "Escape").then(evt => console.log("Esc pressed!", evt));
- If the event fires multiple times, your code will only run the first time.
- If the event fires but the test doesn’t pass, the promise will resolve once it does.
Objects & Arrays
all
Run a method on all elements of an array, get the results as an array.
var ret = $.all(array, method [, args...])
var ret = array._.all(method [, args...])
- array
- The array whose every element we want to run a method on.
- method
- The method name
- args
- Any arguments to pass to the method
- ret
- The array of results. If the method returns no results, this will be the same as
array
.
// Uppercase all strings in an array
["Foo", "bar"]._.all("toUpperCase"); // Returns ["FOO", "BAR"]
Class
Helper for defining OOP-like “classes”, for those who have been irreparably damaged by Java-like languages.
var myClass = $.Class(options);
- options
- An object with the following options:
- constructor
- The constructor.
- extends
- The “class” it inherits from.
- abstract
- If
true
, “classes” can inherit from it, but it will throw an error if called with the new
operator directly. Sorry Java folks, I know this is not what you hoped for.
- lazy
- Lazily evaluated properties. See
$.lazy()
.
- live
- See
$.live()
.
- static
- Any static methods, as a shortcut to
$.extend(myClass, static)
- *
- Any remaining properties will be added on
myClass.prototype
as instance methods.
- To enable more properties with “special” handling, like
lazy
and live
, add them to the $.classProps
object.
each
Loop over properties of an object and map them onto another object.
var ret = $.each(obj, callback [, ret]);
- obj
- The object to loop over
- callback
- The function to be executed for every property. It will be called with
obj
as its context and the property and value as its arguments.
- ret
- The returned object. If not provided, a new object will be created. Provide the same object as
obj
to overwrite.
- Inherited properties will be included in the loop.
extend
Copy properties of an object onto another.
target = $.extend(target, source [, whitelist])
- target
- The object that will receive the new properties.
- source
- An object containing the additional properties to merge in.
- whitelist
- If array or string, a whitelist of property names. If function, it is called on each property and only the properties it returns a truthy value on will be copied. If it’s a regular expression, only matching property names will be copied.
var o1 = {foo: 1, bar:2}
o2 = $.extend(o1, {foo: 3, baz: 4});
// o2 is {foo: 3, bar: 2, baz: 4}
// Get typography-related computed style on <body>
var type = $.extend({},
getComputedStyle(document.body),
/^font|^lineHeight$/);
jQuery.extend
lazy
Define lazily evaluated properties on an object.
object = $.lazy(object, property, getter)
- object
- The object to define the property on.
- property
- The name of the property to define.
- getter
- A function that returns the value of the property. After the first time the property is used, it will be replaced with the return value of this function.
object = $.lazy(object, properties)
- object
- The object to define the properties on.
- properties
- An object where the keys are the property names and the values are the getters.
live
Define properties that behave like normal properties but also execute code upon getting/setting.
object = $.live(object, property, descriptor)
- object
- The object to define the property on.
- property
- The name of the property to define.
- descriptor
- If an object, an accessor descriptor of the property. If a function, it will be assumed to be executed upon setting the property.
$.live(object, properties)
- object
- The object to define the properties on.
- properties
- An object where the keys are the property names and the values are the descriptors.
type
Determine the internal JavaScript [[Class]] of an object.
var type = $.type(object)
- object
- The object whose [[Class]] we want to get.
- type
- The internal [[Class]] of the object, lowercased.
// Check if the second argument of a function is a regexp
if ($.type(arguments[1]) == "regexp") {
// ...
}
jQuery.type
value
Get the value of a nested property reference if it exists, and undefined
without any errors if not.
var val = $.value([obj, ] property1, [property2 [,...[, propertyN]]])
- obj
- The object to use as the root of the property chain. If not provided,
self
will be used
- property1, ..., propertyN
- The properties to resolve on the root object. Order denotes hierarchy.
$.value(document, "body", "nodeType"); // 1
$.value(document, "body", "foo", "bar", "baz"); // undefined, no errors
$.value("document", "body", "nodeType"); // 1, no root, starting from self