The following code demonstrates an Example of onBlur and onFocus Event Handlers in JavaScript.
When an element gets the focus, the onfocus event handler executes. In contrast, when the element has lost the focus, the onblur event handler executes. Both of these event handlers can be used in form validation. For example, we can use onblur to determine whether an input field is left blank or not. Similarly, we can use onfocus to show certain information to user which helps in entering the value in an input field.
The following example shows two input text fields. Also, both of these fields handle blur and focus events. When user clicks on another text field, the previous one fires the blur event. Accordingly, the function f1() executes. Similarly, the function f2() executes when a text field gains the focus.
<html>
<head>
<title>JavaScript Events</title>
<script>
function f1(x)
{
x.style.border='3px red solid';
x.style.backgroundColor='white';
}
function f2(x)
{
x.style.border='1px green solid';
x.style.backgroundColor='skyblue';
}
</script>
<style>
div{
margin: 100px;
padding: 50px;
border: 2px black solid;
text-align: center;
}
</style>
</head>
<body>
<div>
<input type="text" id="t1" onblur="f1(this)" onfocus="f2(this)"/>
<input type="text" id="t2" onblur="f1(this)" onfocus="f2(this)"/>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
What is Asynchronous JavaScript?
Understanding HTTP Requests and Responses
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML