Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
When an element gets the focus, such as a form field, you can use the onfocus
event to trigger a function. onblur
is the opposite - it's like "OnLostFocus".
You can use this to call something else such as resetting a form field back.
Note that we're using this
as an argument so we can use this on any form element
and don't need to write function to worry about which form field to change.
// In HTML:
<element onfocus="myScript"></element>
// In JavaScript:
object.onfocus = function(){myScript};
// In JavaScript, using the addEventListener() method:
object.addEventListener("focus", myScript);
document.getElementById("Hello").addEventListener("focus", function () { RedAlert(this); });
document.getElementById("Hello").addEventListener("blur", function () { YellowAlert(this); });
document.getElementById("Hello2").addEventListener("focus", function () { RedAlert(this); });
document.getElementById("Hello2").addEventListener("blur", function () { YellowAlert(this); });
function RedAlert(control)
{ control.style.background = "#ff0000"; }
function YellowAlert(control)
{ control.style.background = "#ffcc00"; }