JS Events
JS Events
Events are actions that can be detected by JavaScript, and the event object gives information about the event
that has occurred.
Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button.
Events are normally used in combination with functions, and the function will not be executed before the event
occurs!
onblur Event
The onblur event occurs when an object loses focus.
Example
Example
In this example we will execute some JavaScript code when a user leaves an input field:
<html>
<head>
<script type="text/javascript">
function upperCase()
{
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>
<body>
</body>
</html>
onchange Event
The onchange event occurs when the content of a field changes.
Example
Example
In this example we will execute some JavaScript code when a user changes the content of an input field:
<html>
<head>
<script type="text/javascript">
function upperCase(x)
{
var y=document.getElementById(x).value
document.getElementById(x).value=y.toUpperCase()
}
</script>
</head>
<body>
</body>
</html>
onclick Event
The onclick event occurs when an object gets clicked.
Example
Example
In this example the text in the first input field will be copied to the second input field when a button is
clicked:
<html>
<body>
</body>
</html>
ondblclick Event
The ondblclick event occurs when an object gets double-clicked.
Example
Example
In this example the second field changes according to the first field when you double-click on the button:
<html>
<body>
</body>
</html>
onfocus Event
The onfocus event occurs when an object gets focus.
Example
Example
In this example the background color of the input fields change when they get focus:
<html>
<head>
<script type="text/javascript">
function setStyle(x)
{
document.getElementById(x).style.background="yellow"
}
</script>
</head>
<body>
</body>
</html>
onkeydown Event
The onkeydown event occurs when a keyboard key is pressed.