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?
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); } }); }
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With