Advantages of using MooTools addEvent functionality over native JavaScript events
So why use MooTools (or other frameworks) addEvent functionality over an onclick or onblur? For one you are leveraging a framework which has been tested and is widely used so you are minimizing bugs. It also helps separate code from layout much like moving CSS into a stylesheet separates layout and style from the content. Using a frameworks addEvent also looks a lot cleaner than having a bunch of onclicks in the body of your HTML.
Example of adding events to elements on page load using MooTools :
1 2 3 4 5 6 7 8 | window.addEvent('domready', function() { if($('element_id')) { $('element').addEvent('click',function(event){ executeSearchFunction(); }); } }); |
In this example we tell MooTools we want to add an event to the window when the Document Object Model (DOM) is ready, meaning once it is done loading. This ensure that every element defined in your HTML files has loaded before applying events to them. Next we check to see that element_id exists. If it does, which it should, then we specify that we want to add an event of the click type. Then we tell MooTools what code to execute when this event occurs. In this case we want to call a function named executeSearchFunction. This process is very similar for frameworks such as JQuery.
Adding events to elements that do not exist yet:
As of this writing I am not aware of a way to do this without throwing a javascript error, and no, putting the code into a try catch statement is not a solution. Instead when the element is loaded, typically through an XHR aka Ajax request, call a function that adds the events to the newly created elements:
1 2 3 4 5 6 | function loadTableEvents() { $('dgth_name').addEvent('click',function(event){ alert(1); }); } |
Related posts: