Skip to content

Instantly share code, notes, and snippets.

@remy
Last active October 4, 2015 04:57
Show Gist options
  • Save remy/2580925 to your computer and use it in GitHub Desktop.
Save remy/2580925 to your computer and use it in GitHub Desktop.
Tiny selector and event system
$ = function (document) {
var element = Element.prototype,
nodeList = NodeList.prototype,
foreach = [].forEach;
element.on = function () {
element.addEventListener.apply(this, arguments);
return this;
};
nodeList.on = function (event, fn) {
forEach.call(this, function (el) {
el.on(event, fn, false);
});
return this;
};
element.trigger = function (type, data) {
var event = document.createEvent('HTMLEvents');
event.initEvent(type, true, true);
event.data = data || {};
event.eventName = type;
this.dispatchEvent(event);
};
nodeList.trigger = function (event) {
forEach.call(this, function (el) {
el.trigger(event);
});
};
nodeList.forEach = forEach;
return function (s) {
var r = document.querySelectorAll(s);
return r.length == 1 ? r[0] : r;
};
}(document);
$=function(a){var b=Element.prototype,c=NodeList.prototype,d=[].forEach;return b.on=function(){return b.addEventListener.apply(this,arguments),this},c.on=function(a,b){return d.call(this,function(c){c.on(a,b,!1)}),this},b.trigger=function(b,c){var d=a.createEvent("HTMLEvents");d.initEvent(b,!0,!0),d.data=c||{},d.eventName=b,this.dispatchEvent(d)},c.trigger=function(a){d.call(this,function(b){b.trigger(a)})},c.forEach=d,function(b){var c=a.querySelectorAll(b);return 1==c.length?c[0]:c}}(document);

Features

Query elements

var links = $('p:first-child a');

If there is more than one link, the return value is NodeList, if there's only a single match, you have an Element object. So you need to have an idea of what to expect if you want to modify the DOM.

Bind events

$('p:first-child a').on('click', function (event) {
  event.preventDefault();
  // do something else
});

Note: the on and trigger methods are on both Element objects and NodeList objects.

Custom events

$('a').on('foo', function () {
  // foo was fired
});

$('a:first-child').trigger('foo');

Looping

$('p').forEach(function (el) {
  console.log(el.innerHTML);
});

Chaining events

$('a').on('foo', bar).on('click', doclick).trigger('foobar');

Also when a single element is matched, you have access to it:

$('a').href = '/some-place.html';

Gotchas

  • Doesn't fail gracefully like jQuery, if you select something that doesn't return, you won't be able to chain.
  • Trigger doesn't chain. Maybe it should...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment