Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equivalent to $.on

As somebody who (unfortunately) learned more of jQuery than raw javascript I am just now taking the time to replace all of my code with raw javascript. No, it's not needed, but it's an easier way for me to learn. A problem I am facing is converting all of my $(document).on with raw javascript. My website is a "single-page application" and most of my actual HTML is in different files which are called via Ajax requests. So, my question is, how would I look for an event fired from dynamically loaded content? I am assuming I would have to add an onclick event to them, but how is it that jQuery does it without needing an onclick event?

like image 868
Polarize Avatar asked Jun 17 '15 01:06

Polarize


People also ask

What is the jQuery equivalent for on () of JavaScript?

In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.

What does $() mean in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

Is jQuery native JavaScript?

Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.

What is alternative to jQuery?

A progressive JavaScript framework, Vue. js is considered a good alternative to jQuery. It is an open-source, MVVM, front-end JS framework that is considered ideal to create user interfaces and single-page apps. It is also considered good for web interfaces, desktop, and mobile app development.


2 Answers

Binding handlers in native API is done using addEventListener().

To emulate jQuery's event delegation, you could fairly easily create a system that uses the .matches() method to test the selector you give.

function delegate(el, evt, sel, handler) {     el.addEventListener(evt, function(event) {         var t = event.target;         while (t && t !== this) {             if (t.matches(sel)) {                 handler.call(t, event);             }             t = t.parentNode;         }     }); } 

There are probably some tweaks to be made, but basically it's a function that takes the element to bind to, like document, the event type, a selector and the handler.

It starts on the e.target and traverses up the parents until it gets to the bound element. Each time, it checks to see if the current element matches the selector, and if so, it invokes the handler.

So you'd call it like this:

delegate(document, "click", ".some_elem", function(event) {     this.style.border = "2px dashed orange"; }); 

Here's a live demo that also adds dynamic elements to show that new elements are picked up as well.

function delegate(el, evt, sel, handler) {      el.addEventListener(evt, function(event) {          var t = event.target;          while (t && t !== this) {              if (t.matches(sel)) {                  handler.call(t, event);              }              t = t.parentNode;          }      });  }    delegate(document, "click", ".some_elem", function(event) {      this.parentNode.appendChild(this.cloneNode(true));      this.style.border = "2px dashed orange";  });
<div>    <p class="some_elem">      <span>        CLICK ME      </span>    </p>  </div>

Here's a shim to add a bit more support for .matches().

if (!Element.prototype.matches) {   Element.prototype.matches =      Element.prototype.matchesSelector ||      Element.prototype.webkitMatchesSelector ||     Element.prototype.mozMatchesSelector ||     Element.prototype.msMatchesSelector ||      Element.prototype.oMatchesSelector ||      function(s) {         var matches = (this.document || this.ownerDocument).querySelectorAll(s),             i = matches.length;         while (--i >= 0 && matches.item(i) !== this) {}         return i > -1;                 }; } 
like image 114
5 revs, 2 users 88%user1106925 Avatar answered Oct 02 '22 22:10

5 revs, 2 users 88%user1106925


Here is a javascript equivalent to on()

jQuery

$(document).on('click', '#my-id', callback);  function callback(){    ...handler code here } 

Javascript

document.addEventListener('click', function(event) {     if (event.target.id == 'my-id') {       callback();     } }); function callback(){    ...handler code here } 

With this approach, the idea is to make use of event.target. Of course, as the selector changes, your code will have to get more involved

like image 28
AmmarCSE Avatar answered Oct 03 '22 00:10

AmmarCSE