Alternative to 'onclick' for a variable number of links?

172 views
Skip to first unread message

Jeff Dunlap

unread,
Nov 11, 2012, 9:51:14 AM11/11/12
to mootool...@googlegroups.com
I'm learning MooTools and converted some javascript into a MooTools class.

Please note that the number of hyperlinks generated by the server are completely variable.  Although the following appears to work fine is there a better way than using 'onclick'?

<a href="" onclick="myclass.myfunc(param1,param2); return false;">some_text</a>


Arian Stolwijk

unread,
Nov 11, 2012, 9:57:03 AM11/11/12
to mootool...@googlegroups.com

Yes, inline event handlers are in almost all cases a bad idea.

With MooTools you can use .addEvent.

so you have this html:

<a href="#" id="link">some text</a>

and this JS

$('link').addEvent('click', function(event){
    event.preventDefault(); // prevents the default action (which is the "return false" in your code")
    myclass.myfunc(....);
});

If you have more links you can use 

$$('some css selector').addEvent('click', ...);

Or sometimes better:

<div id="parent">
    <a href="#>link 1</a>
    <a href="#>link 1</a>
    <a href="#>link 1</a>
    <a href="#>link 1</a>
</div>

$('parent').addEvent('click:relay(a)', function(event){
    // ...
});

Jeff Dunlap

unread,
Nov 11, 2012, 11:21:46 PM11/11/12
to mootool...@googlegroups.com
Arian,

Thank you for responding.  Your suggestions gave me a good starting point for me to avoid inline event handlers, i.e.:
onclick="myclass.myfunc(param1,param2);

This is what I have so far:

http://jsfiddle.net/jeff_j_dunlap/Dfa5h/

Although I am able to access the parameters, storing them in the hyperlink's href, it does not feel right.  Am I approaching this the wrong way?

Thanks again

Sanford Whiteman

unread,
Nov 11, 2012, 11:55:58 PM11/11/12
to Jeff Dunlap
> Am I approaching this the wrong way?

If you're using eval(), it's *definitely* the wrong way.

See the touchups I made here:

http://jsfiddle.net/Dfa5h/1/

· you can chain addEvent right on the result of $$(). $$() returns an
array of Elements, and you can run any Element method, such as
addEvent() on Elements as well, and it will map each item in the array
to the method

· use data-* attributes and you don't need to pollute the href
attribute, which should be useable in scriptless environments or at
the very least give a nice display in the status bar

· simple split() instead of eval -- eval must be destroyed

-- Sandy

Jeff Dunlap

unread,
Nov 12, 2012, 12:45:14 AM11/12/12
to mootool...@googlegroups.com
Sandy, that's exactly what I needed!  Thank you!

Rolf Langenhuijzen

unread,
Nov 12, 2012, 3:38:06 PM11/12/12
to mootool...@googlegroups.com
gotcha... $$(eval).destroy();
Reply all
Reply to author
Forward
0 new messages