Note: this documentation is autogenerated from the files in src/
The different parts that make Umbrella JS work in the way it works
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)
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
.
An instance of Umbrella JS so you can chain it to any of the other methods.
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);
});
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']);
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).
u
: returns the same instance of Umbrella JS
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)
Add some html as a sibling after each of the matched elements.
.after(html);
html
: a string containing the html that is going to be inserted.
u
: returns the same instance of Umbrella JS
Add a separator <hr>
after each of the main titles h1:
u("h1").after("<hr>");
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);
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){};
Undefined. Please don't use the returned value for anything (it might be a promise in the future).
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');
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);
Add some html as a child at the end of each of the matched elements.
.append(html);
html
: a string containing the html that is going to be inserted.
u
: returns the same instance of Umbrella JS
Add a footer to each of the articles
u("article").after("<footer>Hello world</footer>");
Handle attributes for the matched elements
// GET
.attr('name');
// SET
.attr('name', 'value');
.attr({ name1: 'value', name2: 'value2' });
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
GET
string
: the value of the attribute
SET
u
: returns the same instance of Umbrella JS
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' });
Add some html before of each of the matched elements.
.before(html);
html
: a string containing the html that is going to be inserted.
u
: returns the same instance of Umbrella JS
Add a header to each of the articles
u("article").after("<header>Hello world</header>");
Get the direct children of all of the nodes with an optional filter
.children(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new children as nodes
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
Find the first matched node for each node
.closest(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new ancestors as nodes
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
Loop through all of the nodes and execute a callback for each
.each(callback);
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
});
u
: returns an instance of Umbrella JS with the same nodes
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' });
}
});
Remove unwanted nodes
.filter(filter)
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
andindex
, and the context ofthis
is the instance of umbrella so methods likethis.slice()
are available:
.filter(function(node, index){
// your code
});
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
Get all of the descendants of the nodes with an optional filter
.find(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new children as nodes
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]');
});
-
.closest(filter) get the first ascendant that matches the selector
-
.parent(filter) get all of the direct parents
-
.children(filter) get the direct child of the matched nodes
Add html class(es) to all of the matched elements.
.first();
This method doesn't accept any parameters
The first html node or false if there is none.
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)
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");
name
: a string that represents the class(es) to be matched. To pass several classes they must be separated by an space.
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.
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>
Retrieve or set the html of the elements:
// GET
.html();
// SET
.html(html);
GET should pass no parameter so it retrieves the html.
SET
html
: the new value that you want to set
GET
string
: the html of the first node
SET
u
: returns the same instance of Umbrella JS
Get the main title:
var title = u('h1').html();
Set the main title:
u('h1').html('Hello world');
Check whether any of the nodes matches the selector
.is(filter)
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
andindex
, and the context ofthis
is the instance of umbrella so methods likethis.slice()
are available:
.is(function(node, index){
// your code
});
boolean: true if any of the nodes matches the selector or the function returns true, false otherwise.
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
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)
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.
Umbrella instance
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
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']);
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).
u
: returns the same instance of Umbrella JS
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)
Calls an event on all of the matched nodes
.trigger('submit')
.trigger(new Event('submit', {}));
The only parameter that it accepts is either an event name such as click
, submit
, change
, etc or an event itself.
Umbrella instance
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