js_on_off
js_on_off is a tiny js library (< 3kb) created to have jQuery on() and off() functions with no dependencies. Main features are included:
- JQuery syntax
- event delegation
- remove all event listeners with off
- Works with document, Element, HtmlElement, NodeList and HTMLCollection
- event namespacing
Installation
Use the package manager npm to install js_on_off.
npm install js_on_off --save
Alternatively, you can just download this project from git. Https:
https://github.com/Sanni87/js_on_off.git
Github CLI:
gh repo clone Sanni87/js_on_off
Usage
Once downloaded, there are 2 ways to include this library in your project.
Direct script
You can do it from an html or of course you can reference the script to include on a custom bundle if you want it.
Import module
If you are using tools like webpack, babel, gulp or similars, you can also import the library as follows:
;
Examples
Depending on how the script is included, the syntax of the functions changes slightly. Of course, the functionality doesn't change.
Examples with direct script
As we have said, first of all we must to include the script
Then we can use on or off with direct binding:
var button = document;var { //do stuff}; //direct binding with anonymous functionbutton; //direct binding with named functionbutton; //direct unbindingbutton; //unbind just "handler" for click event on buttonbutton; //unbind all click events on buttonbutton; //unbind everything on button
Event delegation:
<!--[...]--> Click me<!--[...]-->
Namespacing:
var button = document;var { //do stuff}; var { //do stuff}; var { //do stuff}; //bind with namespacebutton; button; button //unbind with namespacebutton; //unbind handler2button; //unbind handler2 and handler3
Examples importing module
If we import the module in a js file, on and off functions will not be attached to NodeList, HtmlElement and so on, so the syntax is a bit different. Here are the same samples using import:
; var parent = document;var button = document;var { //do stuff}; //binding;; ;; //unbinding; //unbind just "handler" for click event on button; //unbind all click events on button; //unbind just "handler" for click event on button; //unbind all click events on button; //unbind attached 'click' events with 'removeThis' namespace on button; //unbind all events with removeThis namespace on button; //unbind everything on button
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.