...

View Full Version : Auto setting event handlers with JS



Code Wizard
01-04-2004, 06:30 PM
Ok,I have the following function:
function changeColor(obj,newColor)
{
obj.style.color=newColor;
}


...Then I have a table(with the id of 'mytable'),in which each cell contains a <p> tag and some text,I want that each <p> tag have an onmouseover and onmouseout event handler defined by JS automaticlly.
->This is the first situation(which doesn't work):
var pars=mytable.getElementsByTagName("p");
for(var i=0;i<pars.length;i++){pars[i].onmouseover=changeColor(this,'red');
pars[i].onmouseout=changeColor(this,'black');
}

->This is the second situation(which works):
var pars=mytable.getElementsByTagName("p");
for(var i=0;i<pars.length;i++){
pars[i].onmouseover=function(){this.style.color='red';}
pars[i].onmouseout=functoin(){this.style.color='black';}
}


My question is...in the first situiation....a function reference(pointer) is assigned to the event handler,so it's obvios the function cannot be assigned with any parameters,so...how can I change it's parameters for the first situation to work???
Thx.

Dennis
01-04-2004, 07:10 PM
try so...

var pars=mytable.getElementsByTagName("p");
for(var i=0;i<pars.length;i++){pars[i].onmouseover="changeColor(this,'red')";
pars[i].onmouseout="changeColor(this,'black')";
}

Code Wizard
01-05-2004, 08:17 PM
Originally posted by Dennis
try so...

var pars=mytable.getElementsByTagName("p");
for(var i=0;i<pars.length;i++){pars[i].onmouseover="changeColor(this,'red')";
pars[i].onmouseout="changeColor(this,'black')";
}


var pars=mytable.getElementsByTagName("p");
for(var i=0;i<pars.length;i++){pars[i].onmouseover=new Function("changeColor(this,'red')");
pars[i].onmouseout=new Function("changeColor(this,'black')");

Now it works...
;)

glenngv
01-06-2004, 05:21 AM
this will also work:

pars[i].onmouseover=function(){changeColor(this,'red')};

Code Wizard
01-06-2004, 04:43 PM
I was wondering:
What's the difference between:
pars[i].onmouseover=function(){changeColor(this,'red')};
and:
pars[i].onmouseover=new Function("changeColor(this,'red')");
?


I mean,in the first case,is a new function object created?
Coz I can't see any other way u can create functions without a name...
Plz reply(this is Very important)...
Thx.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum