loading...

How I become an javascript event magician

ekansss profile image ekanSSS ・2 min read

When I've learn javascript, a few years ago, like a lot of people, I've start JS with a famous framework: jQuery. Event, ajax, dom manipulation, a whole new world to me !

It was simple and easy to use with a good learning curve, but now I've clearly see limitation with it, like a lot of framework, it is extremely slow, and with new navigator, a lot of jQuery feature is directly include in browser, so why not use vanillaJS and fasten up my application and website.

But there are one browser api that haven't much evolved during year: javascript Event. Handle dynamically added elements(delegate) or use custom event is still pain in the ass ! This is why I've developed an utilities to use these functionality like it's magic.

So here come my MagicEvent that extends event functionality to keep it simple with an jQuery like syntax with easy delagate and customs events management.

MagicEvent.on("click", ".clickme", myClickFunc);
MagicEvent.on("slideswitch", ".diapo", slideSwitchHandler);

Here, I just set two listener, one on click for all .clickme elements, and another on each .diapo when I emit an slideswitch custom Event they're no difference between settings the two for ya !

MagicEvent.emit("click", link);
MagicEvent.on("slideswitch", diapoDiv);
MagicEvent.on("slideswitch", diapoDiv, {next: 3});

This time I choose to emit events, it's simple, I just need to choose an event and an element, nor more work, event on custom event, and i can embark custom data if I need, it's easy!

So if you want to try it, here the repo ! And enjoy.

GitHub logo ekanSSS / MagicEvent

Use javascript event like you're a magician

MagicEvent

MagicEvent is one easy and fast event handler in vanillaJS, it natively handle dynamically created Element ! Be the magician !

How it work

It is easy, just call MagicEvent.js in your page then start the fun

<script type="text/javascript" src="pathtoassets/MagicEvent.js"></script>
<script type="text/javascript">
  //here start the fun
<script>

What can we do ?

Listen to an event

To register an event listener just use on method

  //place an event listener for click on a tag
  MagicEvent.on("click", "a", myLinkClickFunc);

Multiple event at once

It handle mutiple event binding in one go

  //place an event listener for click, hover and touch on a tag
  MagicEvent.on("click hover touch", "a", myLinkClickFunc);

CSS Selector

You can select your elements directly by CSS Selector

Even if it's working pretty good, I still working on it so any feedback is appreciated !

Posted on by:

ekansss profile

ekanSSS

@ekansss

Front End developper who love testing weird coding stuff, especially when it touch PWA

Discussion

pic
Editor guide