Skip to content

Instantly share code, notes, and snippets.

@TexRx
Forked from remy/$.js
Created March 15, 2013 16:46
Show Gist options
  • Save TexRx/5171269 to your computer and use it in GitHub Desktop.
Save TexRx/5171269 to your computer and use it in GitHub Desktop.
$ = function (document) {
var element = Element.prototype,
nodeList = NodeList.prototype;
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);
});
};
return function (s) {
var r = document.querySelectorAll(s);
return r.length == 1 ? r[0] : r;
};
}(document);
$=function(e){var d=Element.prototype,f=NodeList.prototype;d.on=function(){d.addEventListener.apply(this,arguments);return this};f.on=function(a,c){[].forEach.call(this,function(b){b.on(a,c,!1)});return this};d.trigger=function(a,c){var b=e.createEvent("HTMLEvents");b.initEvent(a,!0,!0);b.data=c||{};b.eventName=a;this.dispatchEvent(b)};f.trigger=function(a){[].forEach.call(this,function(c){c.trigger(a)})};return function(a){a=e.querySelectorAll(a);return 1==a.length?a[0]:a}}(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');

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