Understanding JavaScript Events
JavaScript events are actions or occurrences that happen in the browser, which can be detected and responded to using JavaScript code. Events form the backbone of interactive web applications, allowing developers to create dynamic user experiences.
In this comprehensive guide, we'll explore two fundamental JavaScript events:
- onblur() - Triggered when an element loses focus
- onclick() - Triggered when an element is clicked
We'll demonstrate these events through a practical example that validates user age and counts words in a text area.
Project Overview
Creating a simple web page to validate the onblur() and onclick event in HTML using simple HTML code and JavaScript to validate.
|
|
| Web Page with Onblur and Onclick Event | Indiantechnoera |
Aim
Create a web page with JS to validate age (onblur event) greater than 18 and count the no of words in the description field (onclick event).
Index Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Onblur(), Onclick() </title>
<style>
.box {border: 2px solid black; padding: 10px; width: 300px; box-shadow: 1px 1px 2px black; border-radius: 5px;}
textarea {resize: none;}
button {cursor: pointer;}
button:hover{background-color: black; color: white; border-radius: 2px;}
</style>
</head>
<body>
<h4>Aim: Create a web page with JS to validate age (onblur event) greater than 18 and count the no of words in the description field (onclick event).</h4>
<center>
<div class="box">
<label for="age">Enter Your Age:</label><br>
<input type="number" id="age" onblur="findAge()"><br>
<label form="inputText">Enter Text:</label>
<textarea name="inputText" id="inputText" cols="30" rows="10" placeholder="Enter your text"></textarea>
<br> <button onclick="calcText()">Calculate </button>
<button onclick="clear_btn()" id="clear_btn">Clear Box</button>
<button onclick="reload_btn()" id="reload_btn">Reload</button>
<br><span id="opTextCount">Count text?</span>
</div>
</center>
<script>
function reload_btn(){
location.reload();
}
function findAge() {
var myAge = document.getElementById("age").value;
if (myAge == 0) {
alert("Your age can't be zero. Pleas enter your correct age.");
} else if (myAge < 0) {
alert("Your age can't be negative. Pleas enter your correct age.");
} else if (myAge < 18) {
alert("Your age is " + myAge + " , under age not allow.");
} else {
alert("Your age is " + myAge + " , adult allow.");
}
}
function clear_btn() {
var boxText = document.getElementById("inputText");
boxText.value = '';
document.getElementById("inputText").innerHTML = boxText;
}
function calcText() {
var str = document.getElementById("inputText").value;
// calculate only words
strW = str;
strW = strW.replace(/(^\s*)|(\s*$)/gi, "");
strW = strW.replace(/[ ]{2,}/gi, " ");
strW = strW.replace(/\n /, "\n");
var strWR = strW.split(' ').length;
// calculate only letters
strL = str;
var strLS = (strL.match(/ /g) || []).length;
var strLR = strL.length - strLS;
// calculate only space
strS = str;
var strSR = (strS.match(/ /g) || []).length;
document.getElementById("opTextCount").innerHTML =
"Total word: " + strWR +
"
Total letter: " + strLR +
"
Total space: " + strSR;
document.getElementById("opTextCount").style.color = 'orange';
document.getElementById("opTextCount").style.fontWeight = 'bold';
document.getElementById("opTextCount").style.fontSize = '25px';
document.getElementById("opTextCount").style.webkitTextStroke = '0.5px black';
}
</script>
</body>
</html>
Output
Code Explanation
OnBlur Event Implementation
The onblur event is attached to the age input field. When the user moves focus away from this field (by tabbing out or clicking elsewhere), the findAge() function is triggered.
The function:
- Retrieves the value from the age input field
- Validates if the age is zero, negative, or less than 18
- Displays appropriate alert messages based on the validation
OnClick Event Implementation
Multiple buttons use the onclick event:
- Calculate Button: Triggers
calcText()function to count words, letters, and spaces in the textarea - Clear Box Button: Triggers
clear_btn()function to empty the textarea - Reload Button: Triggers
reload_btn()function to refresh the page
Text Analysis Function
The calcText() function performs several operations:
- Removes leading and trailing whitespace
- Replaces multiple spaces with single spaces
- Counts words by splitting the text at spaces
- Calculates total characters excluding spaces
- Counts total spaces in the text
- Displays the results with styled formatting
Conclusion
This practical example demonstrates how JavaScript events like onblur and onclick can be used to create interactive web forms. The onblur event is perfect for field validation as it triggers when a user leaves a field, while onclick events provide immediate response to user actions.
Understanding these fundamental events is crucial for web developers looking to create dynamic, user-friendly web applications that respond appropriately to user interactions.