...

View Full Version : onFocus inside SCRIPT tag



jamojo
06-26-2006, 04:43 AM
Hi Everyone!

I just want to know how to call an onFocus event handler inside <SCRIPT> tag.
In the code if i do this, its working:<input name="num3" type="text" id="num3" onfocus="my_onFocus()"/>

here's what i done so far:


<html>
<head>
<title>Untitled Document</title>
</head>
<SCRIPT type="text/javascript">
function my_onFocus() {
document.former.num3.value = parseInt(document.former.num1.value) + parseInt(document.former.num2.value);
}
document.former.num3.onfocus= my_onFocus();
</SCRIPT>
<body>
<form id="former" name="former" method="post" action="">
num1<input name="num1" type="text" id="num1" /><br />
num2<input name="num2" type="text" id="num2" /><br />
Total<input name="num3" type="text" id="num3"/>
</form>
</body>
</html>

I hope you can help me. Thanks in advance!

_Aerospace_Eng_
06-26-2006, 08:23 AM
The form doesn't exist yet so you can't set focus to anything if it doesn't exist. You almost had it, when you are assigning a function to an event you don't put the parentheses.

window.onload = function()
{
document.former.num3.onfocus= my_onFocus;
}

vwphillips
06-26-2006, 09:23 AM
or if you want to pass parameters

document.former.num3.onfocus=function(){ my_onFocus(this.value); }

jamojo
06-26-2006, 09:48 AM
Thanks for the replies. To vwphilips, i did what u told me and call the function in body onload event.

_Aerospace_Eng_
06-26-2006, 09:51 AM
Keeping events out of the markup like onload="somefunction()" is the better way to call a function. You can use vw's code in the same window.onload = that I posted.

jamojo
06-26-2006, 09:53 AM
Thanks _Aerospace_Eng_

vwphillips
06-26-2006, 12:11 PM
BEWARE of window.onload

this may be overidden by or override any other window.onload event


onload event calls must be grouped in one onload event call <BODY>(easiest)

or window(the in thing)

or more complex code used to add rather than replace the event(best)


function zxcEventAdd(zxco,zxct,zxcf) {
if ( zxco.addEventListener ){ zxco.addEventListener(zxct, function(e){ zxco[zxcf](e);}, false); }
else if ( zxco.attachEvent ){ zxco.attachEvent('on'+zxct,function(e){ zxco[zxcf](e); }); }
else {
var zxcPrev=zxco["on" + zxct];
if (zxcPrev){ zxco['on'+zxct]=function(e){ zxcPrev(e); zxco[zxcf](e); }; }
else { zxco['on'+zxct]=zxco[zxcf]; }
}
}

var zxcEvt=0;

function zxcAddEvt(zxco,zxcfun,zxcevt){
if (zxco['zxc'+zxcfun+zxcevt]){ return; }
zxco['zxcaddEvt'+zxcEvt]=window[zxcfun];
zxco['zxc'+zxcfun+zxcevt]=true;
zxcEventAdd(zxco,zxcevt,'zxcaddEvt'+zxcEvt);
zxcEvt++;
}


zxcAddEvt(window,'MyFunction','load');
zxcAddEvt(document,'MyMseMove','mousemove');



this will pass the event to the function as the first parameter
anf the object at this



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum