Balalaika.js
The tiny DOM library (1kB uncompressed and about 600 bytes gzipped!)
Balalaika provides you tiny replacement for huge DOM libraries such as jQuery and Zepto. It contains few methods which should be sufficient for vanilla.js developers.
How can I use it?
First of all you can use it as common library on the web page. Just paste this code to the head
tag:
<script>
window.$=function(t,e,n,i,o,r,s,c,u,f,l,a){"use strict";return a=function(t,e){return new a.i(t,e)},a.i=function(i,o){n.push.apply(this,i?i.nodeType||i==t?[i]:""+i===i?/</.test(i)?((c=e.createElement(o||"q")).innerHTML=i,c.children):(o&&a(o)[0]||e).querySelectorAll(i):/f/.test(typeof i)?/c/.test(e.readyState)?i():a(e).on("DOMContentLoaded",i):i:n)},a.i[l="prototype"]=(a.extend=function(t){for(f=arguments,c=1;c<f.length;c++)if(l=f[c])for(u in l)t[u]=l[u];return t}).call(a,a.fn=a[l]=n,{on:function(t,e){return t=t.split(i),this.map(function(n){(i[c=t[0]+(n.b$=n.b$||++o)]=i[c]||[]).push([e,t[1]]),n["add"+r](t[0],e)}),this},off:function(t,e){return t=t.split(i),l="remove"+r,this.map(function(n){if(f=i[t[0]+n.b$],c=f&&f.length)for(;u=f[--c];)e&&e!=u[0]||t[1]&&t[1]!=u[1]||(n[l](t[0],u[0]),f.splice(c,1));else t[1]||n[l](t[0],e)}),this},is:function(t){return c=this[0],(c.matches||c["webkit"+s]||c["moz"+s]||c["ms"+s]).call(c,t)}}),a}(window,document,[],/\.(.+)/,0,"EventListener","MatchesSelector");
</script>
(Looks like Google Analytics embed)
Then use it anywhere on the web page:
<script>
$(function () {
$('.my-selector').on('click', function () {
alert('I need my balalaika');
});
});
</script>
The second kind of use is using it inside single script as local variable:
(function (win, $) {
// your code starts here
$(function () {
$('.my-selector').on('click', function () {
alert('I need my balalaika');
});
});
// your code ends here
})(window, function(t,e,n,i,o,r,s,c,u,f,l,a){"use strict";return a=function(t,e){return new a.i(t,e)},a.i=function(i,o){n.push.apply(this,i?i.nodeType||i==t?[i]:""+i===i?/</.test(i)?((c=e.createElement(o||"q")).innerHTML=i,c.children):(o&&a(o)[0]||e).querySelectorAll(i):/f/.test(typeof i)?/c/.test(e.readyState)?i():a(e).on("DOMContentLoaded",i):i:n)},a.i[l="prototype"]=(a.extend=function(t){for(f=arguments,c=1;c<f.length;c++)if(l=f[c])for(u in l)t[u]=l[u];return t}).call(a,a.fn=a[l]=n,{on:function(t,e){return t=t.split(i),this.map(function(n){(i[c=t[0]+(n.b$=n.b$||++o)]=i[c]||[]).push([e,t[1]]),n["add"+r](t[0],e)}),this},off:function(t,e){return t=t.split(i),l="remove"+r,this.map(function(n){if(f=i[t[0]+n.b$],c=f&&f.length)for(;u=f[--c];)e&&e!=u[0]||t[1]&&t[1]!=u[1]||(n[l](t[0],u[0]),f.splice(c,1));else t[1]||n[l](t[0],e)}),this},is:function(t){return c=this[0],(c.matches||c["webkit"+s]||c["moz"+s]||c["ms"+s]).call(c,t)}}),a}(window,document,[],/\.(.+)/,0,"EventListener","MatchesSelector"));
Which methods are provided?
Balalaika inherits from Array.prototype
. It means Balalaika can use any method of native arrays.
$('.my-selector').forEach(function (el) {
console.log(el);
});
- concat
- join
- pop
- push
- reverse
- shift
- slice
- sort
- splice
- toString
- unshift
- every
- filter
- forEach
- indexOf
- lastIndexOf
- map
- some
Besides, Balalaika has few additional methods such as:
on
$('.my-selector').on('click.namespace', function () {
alert('I need my balalaika');
});
off
$('.my-selector').off('click.namespace');
is
$('.my-selector').on('click', function (evt) {
if($(evt.target).is('.another-selector')) {
alert('I need my balalaika');
}
});
extend
var myObject = {a:1};
$.extend(myObject, {
b: 2
});
DOM-ready feature
$(function () {
// Do something with DOM
});
It provides very few functions, doesn't it?
Yep. The idea is if you need something, implement it! A lot of jQuery-like functions can be created easily. Use $.fn style to create additional methods:
$.fn.hasClass = function (className) {
return !!this[0] && this[0].classList.contains(className);
};
$.fn.addClass = function (className) {
this.forEach(function (item) {
var classList = item.classList;
classList.add.apply(classList, className.split(/\s/));
});
return this;
};
$.fn.removeClass = function (className) {
this.forEach(function (item) {
var classList = item.classList;
classList.remove.apply(classList, className.split(/\s/));
});
return this;
};
$.fn.toggleClass = function (className, b) {
this.forEach(function (item) {
var classList = item.classList;
if (typeof b !== 'boolean') b = !classList.contains(className);
classList[b ? 'add' : 'remove'].apply(classList, className.split(/\s/));
});
return this;
};
And so on...
More examples
Find elements inside another element
var elements = $('.my-selector', el);
Parse HTML
var elements = $('<div><span class="yeah"></span></div>');
Extended parsing function
Pay attention that the example above doesn't parse contextual elements such as td
, tr
, etc. But the function below does:
$.parseHTML = function (html) {
var node = document.createElement('div'),
// wrapMap is taken from jQuery
wrapMap = {
option: [1, "<select multiple='multiple'>", "</select>"],
legend: [1, "<fieldset>", "</fieldset>"],
thead: [1, "<table>", "</table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
area: [1, "<map>", "</map>"],
_: [0, "", ""]
}, wrapper, i;
html = html.replace(/^\s+|\s+$/g, '');
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
wrapper = wrapMap[/<([\w:]+)/.exec(html)[1]] || wrapMap._;
node.innerHTML = wrapper[1] + html + wrapper[2];
i = wrapper[0];
while (i--) node = node.children[0];
return $(node.children);
};
var myElements = $.parseHTML('<tr><td></td></tr>');
Adding styles for elements
$('.my-selector').forEach(function (el) {
$.extend(el.style, {
width: '30px',
backgroundColor: 'red'
});
});
Delegated events
$('.my-selector').on('click', function (evt) {
var node = evt.target;
while (node !== this) {
if ($(node).is('.delegated-selector')) break; // Handle it!
node = node.parentNode;
}
});
$.fn.parents
plugin
$.fn.parents = function (selector) {
var collection = $();
this.forEach(function (node) {
var parent;
while ((node = node.parentNode) && (node !== document)) {
if (selector) {
if ($(node).is(selector)) parent = node;
} else parent = node;
if (parent && !~collection.indexOf(parent)) collection.push(parent);
}
});
return collection;
};
Licensed under MIT License