Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  105] [ 5]  / answers: 1 / hits: 18038  / 15 Years ago, sat, july 25, 2009, 12:00:00

I'm trying to execute an external function on click of a DOM element without wrapping it in another function.



Say I have a function called sayHello(), as follows:



function sayHello(){
alert(hello);
};


To execute it on click, I currently have to do this:



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


Notice I am forced to wrap the single function call in yet another function.
What I am trying to do is something like this



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


Except that simply doesn't work.
Can I avoid wrapping the single function call in another function in any way?
Thanks!



.



Additional information:
How would I achieve the same thing when I need to pass parameters to the function?



..



Additional information:
Like Chris Brandsma and Jani Hartikainen pointed out, one should be able to use the bind function to pass parameters to the function without wrapping it in another anonymous function as such:



$(#myelement).bind(click, john, sayHello);


with sayHello() now accepting a new parameter, as such:



function sayHello(name){
alert(Hello, +name);
}


This, unfortunately, does not seem to work... Any ideas?
The Events/bind documentation is located here
Thanks!


More From » jquery

 Answers
12

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.


[#99058] Tuesday, July 21, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dasias

Total Points: 344
Total Questions: 100
Total Answers: 100

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
;