views:

58

answers:

7

So I would like to create a function from this:

element.onclick = function(e){
    ... code ...
}

To something like this:

element.onclick  = doSomething(e);
element2.onclick = doSomething(e);

function doSomething(e){
    ... code ...
}

In this way I could call the function multiple times but in this way e is not passed as an event so doesn't works.

How should I do this?

Sry If I say something stupid, this thing is a bit hard to me

A: 

You need to write it in the form of:

function fnName(e){
    ... code ...
}

and then you can call fnName and pass the variable you need.

If your function does not really need the 'e', you can write

function fnName(){
    ...code...
}
Dekker500
You can then say `element.onclick = fnName` and it will work as the first example code in the question does.
BudgieInWA
A: 

Try this

element.onclick = function(event){
... code ...
}
mjw06d
A: 

you can do this:

element.onclick = function(e){

myfunc();

}

function myfunc()

{

... code

}

deepsat
+1  A: 
function onClickHandler(e){
    //Do stuff...
}

element.onclick = onClickHandler;
Rocket
+1  A: 

I think you are asking how to create a normal function and use it in various ways?

function fnName(e) {
  ... code ...
}

Can be used in various ways:

element.onclick = fnName;

fnName();

//Call it however you like?
John Strickler
+3  A: 

Not sure exactly what you mean, but you can declare a function and use it as the handler for multiple elements. The event argument will still be passed.

element.onclick = someHandler;
anotherElem.onclick = someHandler;
yetAnotherElem.onclick = someHandler;

function someHandler(e){
    e = e || event;
    ... code ...
}

Each of the 3 elements will call the same handler, and have the event object as its argument.


EDIT: With regard to your edit, you were calling the function and assigning its return value to onclick instead of assigning the function itself.

Seems from your comment that you figured that out though. :o)

patrick dw
+1  A: 

First you gotta give your function a name.

function clickEvent(e) {
    ... do stuff ...
}

Then attach it onto the element like this:

element.onClick = clickEvent;

When the event is triggered, the event will automatically get passed into the function.

shoebox639