There are addEvent()
and addEvents()
methods that attach an event listener(s) to a DOM element.
Check http://mootools.net/docs/core/Element/Element.Event for documentation.
Is there a Mootools ".on" equivalent?
-
04-07-2023 - |
Question
I am looking for an equivalent to .on()
from jQuery in Mootools. The purpose is to dynamically bind events to elements that are appended to the page after user interactions.
La solution
Autres conseils
It helps if you understand how Event Delgation works.
Here is an example from the page:
// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID!
console.log("List item ",e.target.id.replace("post-")," was clicked!");
}
});
As @dimitar pointed out relay()
is the MooTools way to delegate. In the documentation you can see both some code examples and a jsfiddle.
The syntax would be:
parentElement.addEvent('click:relay(.targetClass)', function(){
Where parentElement
is some element present in the page at the time the JS code is loaded, and .targetClass
would be a class in the target element you want to have delegation for.
As pointed out, there is nice jsFiddle example in the MooTools page, here is another one, adapted from the first one.