Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing jQuery's "live" binder with native Javascript

I am trying to figure out how to bind an event to dynamically created elements. I need the event to persist on the element even after it is destroyed and regenerated.

Obviously with jQuery's live function its easy, but what would they look like implemented with native Javascript?

like image 201
jjhenry Avatar asked Feb 02 '12 02:02

jjhenry


2 Answers

Here's a simple example:

function live(eventType, elementId, cb) {     document.addEventListener(eventType, function (event) {         if (event.target.id === elementId) {             cb.call(event.target, event);         }     }); }  live("click", "test", function (event) {     alert(this.id); }); 

The basic idea is that you want to attach an event handler to the document and let the event bubble up the DOM. Then, check the event.target property to see if it matches the desired criteria (in this case, just that the id of the element).

Edit:

@shabunc discovered a pretty big problem with my solution-- events on child elements won't be detected correctly. One way to fix this is to look at ancestor elements to see if any have the specified id:

function live (eventType, elementId, cb) {     document.addEventListener(eventType, function (event) {         var el = event.target             , found;          while (el && !(found = el.id === elementId)) {             el = el.parentElement;         }          if (found) {             cb.call(el, event);         }     }); } 
like image 147
Andrew Whitaker Avatar answered Sep 23 '22 16:09

Andrew Whitaker


In addition to Andrew's post and Binyamin's comment, maybe this is an option:

With this you can use 'nav .item a' as the selector. Based on Andrew's code.

function live (eventType, elementQuerySelector, cb) {     document.addEventListener(eventType, function (event) {          var qs = document.querySelectorAll(elementQuerySelector);          if (qs) {             var el = event.target, index = -1;             while (el && ((index = Array.prototype.indexOf.call(qs, el)) === -1)) {                 el = el.parentElement;             }              if (index > -1) {                 cb.call(el, event);             }         }     }); }    live('click', 'nav .aap a', function(event) { console.log(event); alert('clicked'); }); 
like image 38
Ro NL Avatar answered Sep 23 '22 16:09

Ro NL