Umbrella JS

Note: this documentation is autogenerated from the files in src/

Find nodes from the HTML with a CSS selector:

u('ul li')
u(document.getElementById('demo'))
u(document.getElementsByClassName('demo'))
u([ document.getElementById('demo'), document.getElementById('test') ])
u('li', context)

Parameters

The first parameter can be:

  • A text CSS selector
  • A single HTML Node. This is specially useful in events where you can just pass this
  • A NodeList or other similar objects that can be converted to an array
  • An array of nodes
  • Nothing

The second parameter is only for the CSS selector, which indicates a portion of the DOM where the selector is applied. For example, with u('li', u('ul').first()) it will find all of the li from the first ul.

Return

An instance of Umbrella JS so you can chain it to any of the other methods.

Examples

Select all of the list elements that are children of ul

var lis = u('ul > li');    // Same as u('ul').children('li');

Find all of the headers from the page to create a Table of Contents:

var headers = u('h1, h2, h3, h4, h5, h6');

It plays well with other libraries, including jquery. For example, with pagex.js:

// When we are on the page "/login"
page(/^login/, function(){

  function done(err, res){
    if (err) return alert("There was an error");
    window.location.href = "/user/" + res.id;
  };

  // Find the form and handle it through ajax when it's submitted
  u("form.login").ajax(done);
});

Native methods

This section is inspired by Bliss.js' vanilla methods

There are many native methods and properties that you can use. These can be called straight in the .first() or .last() elements, a .nodes element or you can loop every element to call them. For example:

// Single element from .nodes
u('h1').nodes[0].classList.add('vanilla');

// Single element
u('h1').first().classList.add('vanilla', 'test');

// Multiple elements
u('h2').each(function(el){
  el.classList.add('vanilla', 'test');
});

And for the arrays it's similar, you can call any array method on u().nodes since this is literally an array:

u('h2').nodes.forEach();
var mapped = u('h2').nodes.map();
var filtered = u('h2').nodes.filter();
var good = u('h2').nodes.some();

However, there are also some advantages of using Umbrella's methods instead of native methods. For example, with .addClass() vs native classList.add():

  • error prevention: if nodes.length = 0, the single-element way will fail in the above implementation (since first() and nodes[0] are null)
  • cross-browser: the classList.add() with multiple elements is not compatible with IE10-11 & Android 4.3-
  • more flexibility: there are many ways to specify multiple classes with addClass, and only one way to specify them on the native way. Imagine that you have an array of classes, with the native method this becomes a nightmare. This is what it means to be flexible:
u('h2').addClass('vanilla', 'test');     // It accepts multiple parameters
u('h2').addClass(['vanilla', 'test']);   // Also accept an array
u('h2').addClass(['vanilla'], ['test']); // Or multiple arrays
u('h2').addClass('vanilla, test');       // Strings with space and/or comma
u('h2').addClass('vanilla', ['test'], 'one, more' }); // Or just whatever

So it's convenient that you know these limitations and act accordingly. Try to use native methods where it makes sense, then Umbrella's methods where it's better suited or then crete your own methods when you need it.

.length

You can check how many elements are matched with .length:

// Check how many <a> are in the page
alert(u('a').length);

.addClass()

Add html class(es) to all of the matched elements.

.addClass('name1');
.addClass('name1 name2 nameN');
.addClass('name1,name2,nameN');
.addClass('name1', 'name2', 'nameN');
.addClass(['name1', 'name2', 'nameN']);
.addClass(['name1', 'name2'], ['name3'], ['nameN']);
.addClass(function(){ return 'name1'; });
.addClass(function(){ return 'name1'; }, function(){ return 'name2'; });

Parameters

name1, name2, nameN: the class name (or variable containing it) to be added to all of the matched elements. It accepts many different types of parameters (see above).

Return

u: returns the same instance of Umbrella JS

Examples

Add the class main to all the <h2> from the page:

u("h2").addClass("main");

Add the class toValidate and ajaxify to all the <form> present in the page:

u("form").addClass("toValidate", "ajaxify");

.removeClass(name) deletes class(es) from the matched elements.

.hasClass(name) finds if the matched elements contain the class(es)

.after()

Add some html as a sibling after each of the matched elements.

.after(html);

Parameters

html: a string containing the html that is going to be inserted.

Return

u: returns the same instance of Umbrella JS

Examples

Add a separator <hr> after each of the main titles h1:

u("h1").after("<hr>");

.before(html)

.append(html)

.prepend(html)

.ajax()

Make all of the matched forms to be submitted by ajax with the same action, method and values when the user submits the form.

Note: this method does NOT submit the form, it just handles it when it's submitted (from the user or with .trigger())

Note2: the .serialize() method used internally is slightly buggy; select can only have a single selection and few other bugs as described here: form serialize javascript

.ajax(done, before);

Parameters

done [optional]: A function to be called when the request ends. The first argument is the error, if any. The second is the body, which is parsed to JSON if it's a JSON string or just the body as a string if it's not JSON. The third is the request object itself.

var done = function(err, body, xhr){};

before [optional]: A function to be called before the request is sent. Useful to manipulate some data in real-time.

var before = function(xhr){};

Return

Undefined. Please don't use the returned value for anything (it might be a promise in the future).

Examples

Handle the newsletter through ajax

u('.newsletter').ajax(function(err){
  if (err) return alert("Error");
  alert("Thank you for subscribing, awesome!");
});

Actually send a form through ajax:

u('form.edit').ajax(function(){ console.log('Sent!'); });
u('form.edit').trigger('submit');

Why not jquery?

This was created because this pattern is quite common in jquery:

$('form').on('submit', function(e){
  e.preventDefault();
  $.post($(this).attr('action'), $(this).serialize(), function(data){
    alert("Done! Thanks, " + data.name);
  }, 'json');
});

After repeating that many times, I found out that it's better if we just make that the default. The same code on Umbrella JS:

u('form').ajax(function(err, data){
  if (!err) alert('Done! Thanks, ' + data.name);
});

Of course you have freedom and you can use a similar method to jquery, but I think it's a bit pointless for this specific situation:

u('form').on('submit', function(e){
  e.preventDefault();
  ajax(u(this).attr('method'), u(this).attr('action'), u(this).serialize(), function(err, data){
    if (!err) alert("Done! Thanks, " + data.name);
  });
});

This is the footprint of the raw function:

ajax(method, url, data, done, before);

.append()

Add some html as a child at the end of each of the matched elements.

.append(html);
.append()

Parameters

html: a string containing the html that is going to be inserted or a function that returns the data, defaults [""]: an array of elements which will passed to the callback. The callback is executed once per element, and all of them are appended consecutively

Return

u: returns the same instance of Umbrella JS

Examples

Add a footer to each of the articles

u("article").append("<footer>Hello world</footer>");

Add three elements to the list. All of these methods are equivalent:

// Add them all like a single string
u("ul").append("<li>One</li><li>Two</li><li>Three</li>");

// Add them in a chain
u("ul").append("<li>One</li>").append("<li>Two</li>").append("<li>Three</li>");

// Add them with a function parameter
var cb = function(txt){ return "<li>" + txt + "</li>" };
u("ul").append(cb, ["One", "Two", "Three"]);

// Same as the previous one but with ES6
u("ul").append(txt => `<li>${ txt }</li>`, ["One", "Two", "Three"]);

.prepend(html)

.before(html)

.after(html)

.attr()

Handle attributes for the matched elements

// GET
.attr('name');

// SET
.attr('name', 'value');
.attr({ name1: 'value', name2: 'value2' });

Parameters

GET name: the attribute that we want to get from the first matched element

SET name: the attribute that we want to set for all of the matched elements value: what we want to set the attribute to. If it's not defined, then we get the name

Return

GET string: the value of the attribute

SET u: returns the same instance of Umbrella JS

Important

You must understand that .attr() will only retrieve the attributes, not the properties like checked. To understad it better, check jquery's attr() vs prop().

Each property is different so you should consult each case. For example, if you wanted to get the property checked you could do:

u('.terms-os-service').is(':checked');

Examples

Get the alt of an image:

u('img.hero').attr('alt');

Set the src of all of the images:

u('img').attr({ src: 'demo.jpg' });

.data() handle data-* attributes for the matched elements

.before()

Add some html before of each of the matched elements.

.before(html);

Parameters

html: a string containing the html that is going to be inserted.

Return

u: returns the same instance of Umbrella JS

Examples

Add a header to each of the articles

u("article").after("<header>Hello world</header>");

.after(html)

.append(html)

.prepend(html)

.children()

Get the direct children of all of the nodes with an optional filter

.children(filter);

Parameters

filter: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation

Return

u: returns an instance of Umbrella JS with the new children as nodes

Examples

Get the first <li> of every <ul>

u("ul").children('li:first-child');

.parent(filter) get all of the direct parents

.find(filter) get all of the descendants of the matched nodes

.closest(filter) get the first ascendant that matches the selector

.closest()

Find the first matched node for each node

.closest(filter);

Parameters

filter: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation

Return

u: returns an instance of Umbrella JS with the new ancestors as nodes

Examples

Get the ul of every li

u("li").closest('ul');

.find(filter) get all of the descendants of the matched nodes

.parent(filter) get all of the direct parents

.children(filter) get the direct children of all of the nodes with an optional filter

.data()

Handle data-* attributes for the matched elements

// GET
.data('name');

// SET
.data('name', 'value');
.data({ name1: 'value', name2: 'value2' });

Parameters

GET name: the data-* attribute that we want to get from the first matched element

SET name: the data-* attribute that we want to set for all of the matched elements value: what we want to set the attribute to. If it's not defined, then we get the name

Return

GET string: the value of the data-* attribute

SET u: data-* returns the same instance of Umbrella JS

Examples

Get the value for data-id:

<ul>
  <li data-id='0'>First</li>
  <li data-id='1'>Second</li>
  <li data-id='2'>Third</li>
</ul>
u('ul li').first().data('id'); // 0

Set the data-id of an element:

u('ul li').first().data({ id: '1' }); // <li data-id='1'>First</li>

u('ul li').first().data('id', '2'); // <li data-id='2'>First</li>

.attr() handle attributes for the matched elements

.each()

Loop through all of the nodes and execute a callback for each

.each(callback);

Parameters

callback: the function that will be called. It accepts two parameters, the node and the index, and the context for this is Umbrella's instance so other methods like this.args() and this.slice() are available.

.each(function(node, i){
  // work
});

Return

u: returns an instance of Umbrella JS with the same nodes

Examples

Loop through all of the links and add them a target="_blank":

u('a').each(function(node, i){
  if (!/^\//.test(node.attr('href'))){
    u(node).attr({ target: '_blank' });
  }
});

.filter()

Remove unwanted nodes

.filter('a')
.filter(u('a'))
.filter(function(node, index){ u(node).is('a'); })

Parameters

filter: it can be:

  • css selector that each of the nodes must match to stay
  • instance of umbrella with the element to keep
  • function that returns a boolean with true to keep the element. It accepts two parameters, node and index, and the context of this is the instance of umbrella so methods like this.slice() are available:
.filter(function(node, index){
  // your code
});

Examples

Get only the active links

var links = u('a').filter('.active');

Get all of the paragraphs with a link:

var paragraphs = u('p').filter(function(node){
  return u(node).find('a').nodes.length > 0;
});

Filter the inputs to those with an answer above 5 and show an error:

u('input').filter(function(node, i){
  if (parseInt(u(node).html()) > 5) {
    return true;
  }
}).addClass('error');

.is(filter) check whether one or more of the nodes is of one type

.find()

Get all of the descendants of the nodes with an optional filter

.find(filter);

Parameters

filter: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation

Return

u: returns an instance of Umbrella JS with the new children as nodes

Examples

Get all of the links within a paragraph

u("p").find('a');

Get the required fields within a submitting form:

u('form').on('submit', function(e){
  var required = u(this).find('[required]');
});

.first()

Add html class(es) to all of the matched elements.

.first();

Parameters

This method doesn't accept any parameters

Return

The first html node or false if there is none.

Examples

Retrieve the first element of a list:

var next = u("ul.demo li").first();

.removeClass(name) deletes class(es) from the matched elements.

.hasClass(name) finds if the matched elements contain the class(es)

.hasClass()

Find if any of the matched elements contains the class passed:

.hasClass(name1, name2)
u("a").hasClass("button")

You can also check multiple classes with the AND condition:

u("a").hasClass("button primary")

This would be similar to:

u("a").hasClass("button") && u("a").hasClass("primary");

Parameters

name: a string that represents the class(es) to be matched. To pass several classes they must be separated by an space.

Return

boolean: returns true if all of the passed classes are found in any of the matched elements and false if they couldn't be found.

.addClass(name) adds html class(es) to each of the matched elements.

.removeClass(name) deletes class(es) from the matched elements.

Example

Toggle the color of a button depending on the status

    <a class="example button">Click me</a>

    <script src="//umbrellajs.com/umbrella.min.js"></script>
    <script>
      u(".example").on('click', function() {
        if(u(this).hasClass("error")) {
          u(this).removeClass("error").html("Click me");
        } else {
          u(this).addClass("error").html("Confirm");
        }
      });
    </script>

.html()

Retrieve or set the html of the elements:

// GET
.html();

// SET
.html(html);

Parameters

GET should pass no parameter so it retrieves the html.

SET html: the new value that you want to set

Return

GET string: the html of the first node

SET u: returns the same instance of Umbrella JS

Examples

Get the main title:

var title = u('h1').html();

Set the main title:

u('h1').html('Hello world');

.attr(html)

.is()

Check whether any of the nodes matches the selector

.is('a')
.is(u('a'))
.is(function(){ return Math.random() > 0.5 })

Parameters

filter: it can be two things:

  • css selector to check
  • instance of umbrella with the elements to check
  • function that returns a boolean to check for each of the nodes. If one of them returns true, then the method is() returns true. It accepts two parameters, node and index, and the context of this is the instance of umbrella so methods like this.slice() are available:
.is(function(node, index){
  // your code
});

Return

boolean: true if any of the nodes matches the selector or the function returns true, false otherwise.

Examples

Check if the current form needs to be valdated

u('form.subscribe').ajax(false, function() {

  // Same as u('form.subscribe').hasClass('validate')
  if (u('form.subscribe').is('.validate')) {
    validate();
  }
});

.filter() remove unwanted nodes

.not()

Remove known nodes from nodes

.not('a')
.not(u('a'))
.not(function(node){ return Math.random() > 0.5; })

Parameters

not: it can be two things (in order):

  • css selector that each of the nodes must not match to stay
  • instance of umbrella with the element to remove
  • function that returns true to remove the element. It accepts one parameter, and the context of this is the instance of umbrella so methods like this.slice() are available
.not(function(node){
  // your code
});

Examples

<ul class="menu">
    <li><a class="active">Menu item 1</a></li>
    <li><a>Menu item 2</a></li>
    <li><a>Menu item 3</a></li>
</ul>

Get only the non-active links on paragraphs

var nonactive_links = u('.menu a').not('.active');

Get all of the active:

active_links = u('.menu a').not(nonactive_links);

.on()

Calls a function when an event is triggered

.on('event1', callback)
.on('event1 event2 eventN', callback)
.on('event1,event2,eventN', callback)
.on(['event1', 'event2', 'eventN'], callback)

Parameters

event1, event2, eventN: the name(s) of the events to listen for actions, such as click, submit, change, etc. callback: function that will be called when the event is triggered. It accepts a single parameter, the event itself.

Return

Umbrella instance

Examples

An auto-save feature that submits the form through ajax every 10 seconds

// Show 'test' when the button test is clicked
u('button.test').on('click', function(e) {
  alert("Test");
});

// This example is very similar to .ajax() implementation
u('form.test').on('submit', function(e){

  // Avoid submitting the form normally
  e.preventDefault();

  // Submit the form through ajax
  ajax(u(this).attr('action'), u(this).serialize());
});

// Better 'onchange':
u('input').on('change click blur paste', function(){
  console.log("Maybe changed");
});

.trigger() calls an event on all of the matched nodes

.prepend()

This method is similar to append. However note that, unlike append, the elements are inserted in inverse order. So all of these methods are equivalent:

// Add them all like a single string
u("ul").prepend("<li>One</li><li>Two</li><li>Three</li>");

// Add them in a chain
u("ul").prepend("<li>Three</li>").append("<li>Two</li>").append("<li>One</li>");

// Add them with a function parameter
var cb = function(txt){ return "<li>" + txt + "</li>" };
u("ul").prepend(cb, ["Three", "Two", "One"]);

// Same as the previous one but with ES6
u("ul").prepend(txt => `<li>${ txt }</li>`, ["Three", "Two", "One"]);

And they will yield:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>

  <!-- previous data -->
</ul>

You can fix this in the method that accepts data with a simple .reverse(). This will yield the same html:

u("ul").prepend(cb, ["One", "Two", "Three"].reverse());

However, as it should be obvious, it cannot be reversed in the chainable method.

.remove()

Removes the matched elements.

.remove();

Parameters

This method doesn't accept any parameters

Return

u: Returns an instance of Umbrella JS with the removed nodes.

Examples

Remove all the elements of a list:

u("ul.demo li").remove();

.removeClass()

Remove html class(es) to all of the matched elements.

.removeClass('name1');
.removeClass('name1 name2 nameN');
.removeClass('name1,name2,nameN');
.removeClass('name1', 'name2', 'nameN');
.removeClass(['name1', 'name2', 'nameN']);
.removeClass(['name1', 'name2'], ['name3'], ['nameN']);

Parameters

name1, name2, nameN: the class name (or variable containing it) to be removed to all of the matched elements. It accepts many different types of parameters (see above).

Return

u: returns the same instance of Umbrella JS

Examples

Remove the class main to all the <h2> from the page:

u("h2").removeClass("main");

Remove the class toValidate and ajaxify to all the <form> present in the page:

u("form").removeClass("toValidate", "ajaxify");

.addClass(name) adds class(es) from the matched elements.

.hasClass(name) finds if the matched elements contain the class(es)

.siblings()

Get the siblings of all of the nodes with an optional filter

.siblings(selector);

Parameters

selector: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation

Return

u: returns an instance of Umbrella JS with the new siblings as nodes

Examples

Get the all the siblings of the hovered <li>

u("li:hover").siblings('li:first-child');

Get all the siblings

u("li").siblings();

.toggleClass()

Toggles html class(es) to all of the matched elements.

.toggleClass('name1');
.toggleClass('name1 name2 nameN');
.toggleClass('name1,name2,nameN');
.toggleClass(['name1', 'name2', 'nameN']);
.toggleClass('name1', forceAdd);

Parameters

name1, name2, nameN: the class name (or variable containing it) to be toggled to all of the matched elements. It accepts many different types of parameters (see above).

forceAdd: boolean telling the method whether to force an .addClass() (true) or .removeClass() (false).

Return

u: returns the same instance of Umbrella JS

Examples

Add the class main to all the <h2> from the page:

u("h2").toggleClass("main");

Add the class toValidate and remove ajaxify from the element <form class="ajaxify"> present in the page:

u("form.ajaxify").toggleClass("toValidate ajaxify");

Force an .addClass() on the element <h2> from the page:

u("h2").toggleClass("main", true);

Note however that this last example by itself doesn't make much sense as you could just use addClass() instead. It makes a lot more sense when the second parameter is checked dynamically:

u("h2").toggleClass("main", u('.accept').is(':checked'));

.addClass(name) adds class(es) from the matched elements.

.removeClass(name) deletes class(es) from the matched elements.

.hasClass(name) finds if the matched elements contain the class(es)

.trigger()

Calls an event on all of the matched nodes

.trigger('submit')
.trigger(new Event('submit', {}));

Parameters

The only parameter that it accepts is either an event name such as click, submit, change, etc or an event itself.

Return

Umbrella instance

Examples

An auto-save feature that submits the form through ajax every 10 seconds

// Make the form to submit through ajax
u('form.edit').ajax();

// Submit it every 10s
setInterval(function(){
  u('form.edit').trigger('submit');
}, 10000);

.on() add an event listener to thematched nodes