Useful Resources
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses
Onfocus and onblur

Onfocus and Onblur

Onfocus is an event that is usually used with text forms and is triggered when a text form element is activated buy someone clicking in the text entry area. Onblur is triggered when you click outside the text area or on another text element. You can call a javascript function when the onfocus or onblur of a form element is activated.

Example:

The HTML and Javascript Code:

<head>
      <script type="text/javascript">
            function changeValueFocus() {
                  document.myForm.myText.value = "I am focused now - click on something else";
            }

            function changeValueBlur() {
                  document.myForm.myText.value = "Blurry vision - help - click me to focus";
            }
      </script>
</head>

<body>
      <form name="myForm">
            <input type="text" name="myText" size="40" value="Click to give me focus"
            onFocus="changeValueFocus()" onBlur="changeValueBlur()">
      </form>
</body>


A more useful thing to do might be to empty a text field once the user has clicked on the text field:


<head>
      <script type="text/javascript">
            function clearForm() {
                  if (document.myOtherForm.myField.value == "Click me!") {
                        document.myOtherForm.myField.value = "";
                  }
            }
            function fillForm() {
                  if (document.myOtherForm.myField.value == "") {
                        document.myOtherForm.myField.value = "Click me!";
                  }
            }
      </script>
</head>

<body>
      <form name="myOtherForm">
            <input type="text" name="myField" value="Click me!" onFocus="clearForm()" onBlur="fillForm()">
      </form>
<body>

Be Creative! You can change the position of a div, you can hide or show something, you can swap images like in a rollover, you can add text to a different field, etc. Anything you can do in a function can be done when you click in a textbox or leave the textbox.

[BACK to RESOURCES]