Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active March 27, 2021 19:10
Show Gist options
  • Save WebReflection/13a3682240c83d2a657d2882e56d1bc6 to your computer and use it in GitHub Desktop.
Save WebReflection/13a3682240c83d2a657d2882e56d1bc6 to your computer and use it in GitHub Desktop.
The smallest, cross browser, DOM chainable `.on()` shortcut for `addEventListener`
(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;
}
}
));
@WebReflection
Copy link
Author

WebReflection commented Sep 15, 2016

296 bytes uncompressed, 224 gzipped:

(function(F,I,X,D,o){D=(F.Node||F.Element).prototype;o=F.Object.defineProperty||function(t,k,d){t[k]=d.value};I in F||o(F,I,X);I in D||o(D,I,X);I in F.document||o(F.document,I,X)}(window,'on',{writable:1,configurable:1,value:function(){return this.addEventListener.apply(this,arguments),this}}));

Live test: http://www.3site.eu/on/

@WebReflection
Copy link
Author

WebReflection commented Sep 16, 2016

Compatibility

IE8 (including conditionally ie8) as well as every other browser I could test.

@bigopon
Copy link

bigopon commented Feb 10, 2017

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