Skip to content

Latest commit

 

History

History
928 lines (525 loc) · 16.3 KB

documentation.md

File metadata and controls

928 lines (525 loc) · 16.3 KB

Umbrella JS

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

The different parts that make Umbrella JS work in the way it works

u()

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);
});

.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']);

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");

Related

.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>");

Related

.before(html)

.append(html)

.prepend(html)

.ajax()

Make all of the matched forms to be submitted by ajax with the same 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())

.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);

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 footer to each of the articles

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

Related

.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

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' });

Related

.html(html)

.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>");

Related

.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');

Related

.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');

Related

.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(filter)

Parameters

filter: it can be two things:

  • css selector that each of the nodes must match to stay
  • 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');

Related

  • .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]');
});

Related

.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();

Related

.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.

Related

.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');

Related

.attr(html)

.is()

Check whether any of the nodes matches the selector

.is(filter)

Parameters

filter: it can be two things:

  • css selector that each of the nodes must match to stay
  • 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:
.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();
  }
});

Related

.filter() remove unwanted nodes

.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");
});

Related

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

.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");

Related

.addClass(name) adds 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);

Related

.on() add an event listener to thematched nodes