How can I execute an external function when an element is clicked?

$("#myelement").click(sayHello());

This is actually calling sayHello() before you set the click handler. It's trying to set the return value of sayHello() as the callback function!

Instead, try:

$("#myelement").click(sayHello);

And regarding your edit, if you need to pass parameters you can just use the closure technique you're already using, but if you're looking for something cleaner then check out How can I pass a reference to a function, with parameters?


You are calling the sayHello-function, you can pass it by reference by removing the parenthesis:

$("#myelement").click(sayHello);

Edit: If you need to pass parameters to the sayHello-function, you will need to wrap it in another function. This defines a parameter-less new function that calls your function with the parameters provided at creation-time:

$("#myelement").click(function () {
   sayHello('name');
   // Creates an anonymous function that is called when #myelement is clicked.
   // The anonymous function invokes the sayHello-function
});

To pick up from a question you had in there.

Obviously, you need to call it this way to work:

$("#myelement").click(sayHello);

Calling it the way you had it actually executes the method instead of sending the method to the click handler.

If you need to pass data you can also call the method this way:

$("#myelement").click(function(){ sayHello("tom");});

Or you can pass data via the bind() function

function sayHello(event){ alert("Hello, "+event.data); }

$("#myelement").bind("click", "tom", sayHello);

Or you can retrieve data from the element that was clicked

$("#myelement").click(function(){sayHello($(this).attr("hasData");});.

Hope that helps.