Adam Halasz
Adam Halasz

Reputation: 58301

Function for an event

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?

Upvotes: 2

Views: 211

Answers (6)

user113716
user113716

Reputation: 322492

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)

Upvotes: 3

shoebox639
shoebox639

Reputation: 2312

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.

Upvotes: 1

John Strickler
John Strickler

Reputation: 25421

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?

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

function onClickHandler(e){
    //Do stuff...
}

element.onclick = onClickHandler;

Upvotes: 1

zerodin
zerodin

Reputation: 877

you can do this:

element.onclick = function(e){

myfunc();

}

function myfunc()

{

... code

}

Upvotes: -1

Dekker500
Dekker500

Reputation: 821

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...
}

Upvotes: 0

Related Questions