PDA

View Full Version : onclick event with parameters


aEr_aEr
11-01-2002, 08:22 AM
I want to call a function with a onclick event with parameters
but that won't work i've got this code


menuOptie = menuObject.appendChild(document.createElement("DIV"));
menuOptie.innerHTML="Borders";
menuOptie.className="menuitems";
menuOptie.onclick=swithBorders;


switchborders function:

function switchBorders(iFrameId, switchStyle){
code to execute
}


How can i get the onclick event to do

switchBorders(editHTML,true);


so how can i assign a funciton with parameters to the onclick event.

mordred
11-01-2002, 02:24 PM
Perhaps like this?


menuOptie.onclick= function() {
switchBorders(editHTML,true);
}


Or alternatively, make a search for addEventListener() or attachEvent().

BrainJar
11-01-2002, 02:51 PM
Technically, event handers take only one argument, and event object. (IE's proprietary event model doesn't even have that, you have to use the global window.event object).

Try this:

<a href="" onclick="alert(this.onclick);return false">test</a>

You should see something like:

function onclick(event) {
alert(this.onclick);
return false;
}

or (in IE):

function anonymous() {
alert(this.onclick);
}

because onclick="alert(this.onclick);return false" creates an anonymous function.

Same with using the .onclick property on a DOM element. You give it the name of the function which should be defined to accept a single argument, the event object.

If you need to access other parameters, you can assign them as new properties on the DOM element:

menuOptie.arg1 = editHTML;
menuOptie.arg2 = true;
menuOptie.onclick=swithBorders;

then access them from within the handler using the this keyword:

function switchBorders(event){

var iFrameId = this.arg1;
var switchStyle = this.arg2;
// other code...
code to execute
}

beetle
11-01-2002, 02:58 PM
I've used the method mordred shows before. Seems to work fine.