JavaScript » eventhandler » onFocus

onFocus = myJavaScriptCode

Event handler for Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window.

The onFocus event handler executes the specified JavaScript code or function on the occurance of a focus event. This is when a window, frame or form element is given focus. This can be caused by the user clicking on the current window, frame or form element, by using the TAB key to cycle through the various elements on screen, or by a call to the window.focus method. Be aware that assigning an alert box to an object's onFocus event handler with result in recurrent alerts as pressing the 'o.k.' button in the alert box will return focus to the calling element or object.

The onFocus event handler uses the following Event object properties.

type - this property indicates the type of event.
target - this property indicates the object to which the event was originally sent.


<input type="text" name="myText" value="Give me focus" onFocus = "changeVal()">

<script type="text/javascript" language="JavaScript">

s1 = new String(myForm.myText.value)

function changeVal() {
   s1 = "I'm feeling focused"
   document.myForm.myText.value = s1.toUpperCase()


This example shows the use of the onFocus event handler to replace the default string displayed in the text box. Note that the first line is HTML code and it is accepted that the text box resides on a form called 'myForm'.

See Also: