After my previous post about MooTools Basic Tips for web designer I received a lot of excited messages from my readers, lovers of this beautiful framework, for this session of lessons dedicated to MooTools. Thanks a lot guys! I really appreciate your support! So... a question which a lot of peopole asked to me was how it's possible to get the ID of an element (for example the ID of an element into a list) and associate to this element some event (change background, display an alert message...). In this post I want to illustrate how to get the ID of DOM elements using MooTools and unobtrusive elegant code.
1. An "Obtrusive" way to implement it
Before to explain how to do it with MooTools, I think it's better take a look at the following HTML code:
alert("The ID of the list element you've chosen is: li_"+listElement);
2. The unobtrusive way to implement it using MooTools
Ok, now we are ready to see how we can implement the same script using unobtrusive code with MooTools. First, take a look at the HTML code:
<li id="li_2"><a href="#">Get this ID</a></li>
<li id="li_3"><a href="#">Get this ID</a></li>
What's changed from the step 1? I removed onClick event within each link:
Copy and paste the following code within the <head> tag:
... and now copy, below the previous code, the following:
alert("The ID of the list element you've chosen is: "+listID);
How you can see, I used getElements() method to get all <li> tags within <ul> list with ID "myList ". Every times you click on <a> element contained into a <li> tag, the function display an alert window with the ID of the element you've chosed, passing the ID using .pass(el.id) method. It's all and it's very simple!
Take a look at the source code:
Download source code
Add a comment for other info or request!
MooTools Basic Tips for Web Designer (Lesson 1)