View Full Version : onFocus inside SCRIPT tag

06-26-2006, 03: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:

<title>Untitled Document</title>
<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();
<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"/>

I hope you can help me. Thanks in advance!

06-26-2006, 07: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;

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

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

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

06-26-2006, 08: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.

06-26-2006, 08:53 AM
Thanks _Aerospace_Eng_

06-26-2006, 11:11 AM
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; }


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