Last active
March 27, 2021 19:10
-
-
Save WebReflection/13a3682240c83d2a657d2882e56d1bc6 to your computer and use it in GitHub Desktop.
The smallest, cross browser, DOM chainable `.on()` shortcut for `addEventListener`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (F, I, X, DOM, on) { | |
DOM = (F.Node || F.Element).prototype; | |
on = F.Object.defineProperty || | |
function (t, k, d) { | |
t[k] = d.value; | |
}; | |
I in F || on(F, I, X); | |
I in DOM || on(DOM, I, X); | |
I in F.document || on(F.document, I, X); | |
}( | |
window, | |
'on', | |
{ | |
writable: true, | |
configurable: true, | |
value: function on() { | |
this.addEventListener.apply(this, arguments); | |
return this; | |
} | |
} | |
)); |
Compatibility
IE8 (including conditionally ie8) as well as every other browser I could test.
Sorry couldn't resist when you support on
without un
😄
(function (F, I, X, U, Y, DOM, on, targets, i) {
DOM = (F.Node || F.Element).prototype;
on = F.Object.defineProperty ||
function (t, k, d) {
t[k] = d.value;
};
targets = [F, F.document, DOM];
for (i =0; i < 3; ++i) {
I in targets[i] || on(targets[i], I, X);
U in targets[i] || on(targets[i], U, Y);
}
}(
window,
'on',
{
writable: true,
configurable: true,
value: function on() {
this.addEventListener.apply(this, arguments);
return this;
}
},
'un',
{
writable: true,
configurable: true,
value: function un() {
this.removeEventListener.apply(this, arguments);
return this;
}
}
));
Compressed (Closure compiler):
(function(b,e,h,f,k,g,d,c,a){g=(b.Node||b.Element).prototype;d=b.Object.defineProperty||function(a,b,c){a[b]=c.value};c=[b,b.document,g];for(a=0;3>a;++a)e in c[a]||d(c[a],e,h),f in c[a]||d(c[a],f,k)})(window,"on",{writable:!0,configurable:!0,value:function(){this.addEventListener.apply(this,arguments);return this}},"un",{writable:!0,configurable:!0,value:function(){this.removeEventListener.apply(this,arguments);return this}});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
296 bytes uncompressed, 224 gzipped:
Live test: http://www.3site.eu/on/