Java Script Part- 2
What Are JavaScript Events?
Definition:
Actions that occur in the browser and can be handled using JavaScript.
Examples:
Clicking a button, hovering over a link, typing in an input.
Types of JavaScript Events:
There are several types of JavaScript events, including:
• Mouse events (click, hover, etc.)
• Keyboard events (keypress, keydown, etc.)
• Form events (submit, change, etc.)
Handling Click Events
Definition:
Click events are triggered when an element is clicked.
Examples:
document.getElementById("button").addEventListener("click", function(){ alert("Button
clicked!"); });
Handling Hover Events
Definition:
Hover events are triggered when the mouse is moved over an element.
Examples:
document.getElementById("element").addEventListener("mouseover", function(){ alert("Mouse
over!"); });
Handling Keypress Events
Definition:
Keypress events are triggered when a key is pressed.
Examples:
•document.addEventListener("keypress", function(event){ alert("Key pressed: " + event.key); });
Inline Event Handlers (Not Recommended)
Example:
<button onclick="alert('Clicked!')">Click Me</button>
Why avoid: Poor separation of concerns
Event Listener Method (Recommended)
•addEventListener() is the modern, clean approach
•Allows multiple listeners on one element
Preventing Default Behavior
•Prevent form from submitting or link from navigating
•form.addEventListener("submit", function(e) {
• e.preventDefault();});
Form Validation?
•Form validation is the process of checking user input to ensure it meets certain criteria.
•Ensuring user input is correct before submission
•Types: Required fields, email format, password length, etc.
Why Use JavaScript for Validation?
• Instant feedback
• Reduce server load
• Improve user experience
Required Field Validation
•if (document.getElementById("name").value === "") {
• alert("Name is required");}
Description: Basic form validation involves checking user input using JavaScript.
Example:
if (document.getElementById("username").value.length < 5) { alert("Username must be at least
5 characters long!"); }
Email Validation Example
•let email = document.getElementById("email").value;
•let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
•if (!pattern.test(email)) {
• alert("Enter a valid email");
•}
Password Strength Check
•let password = document.getElementById("pwd").value;
•if (password.length < 6) {
• alert("Password must be at least 6 characters");}
Confirm Password Match
if (pwd !== confirmPwd) {
alert("Passwords do not match");
}
JavaScript Events
Definition:
JavaScript events are actions that occur on a web page, such as clicking a button or hovering
over an element.
Examples:
Example: document.getElementById("button").addEventListener("click", function()
{ alert("Button clicked!"); });
Real-time Validation with input Event
Definition:
•Live feedback as the user types
Example:
input.addEventListener("input", function() {
// validate and give feedback
});
Displaying Errors in the Page
Definition:
•Show errors in a <div> instead of using alert()
Example:
•document.getElementById("error").textContent = "Invalid input!";
Introduction to Local Storage
•Local storage allows data to be stored locally on the client-side.
•Data persists even after browser is closed
•Example:
• localStorage.setItem("key", "value");
•localStorage.setItem("username", "John");
•console.log(localStorage.getItem("username"));
Benefits of Local Storage
Local storage provides several benefits, including:
Example:
- Faster data access
- Reduced server load
- Improved offline support
Removing & Clearing Storage
localStorage.removeItem("username");
localStorage.clear();
Introduction to Session Storage
Description:
- Session storage is similar to local storage, but data is only stored for the duration of the session.
- Data is cleared when browser/tab is closed
- Example:
- sessionStorage.setItem("key", "value");
- sessionStorage.setItem("tempScore", 100);
Benefits of Session Storage
Session storage provides several benefits, including:
- Automatic data cleanup
- Improved security
- Reduced storage needs
Using Session Storage
Description:
Session storage can be used to store temporary data, such as:
- Form data
- Temporary calculations
- Session-specific data
Local Storage vs Session Storage
Description:
- Local storage and session storage have different use cases:
- Local storage: persistent data
- Session storage: temporary data
Best Practices for Local Storage
and Session Storage
Use them carefully: Only store essential data in local storage or session storage to avoid
confusion and potential performance issues.
Validate user input: Ensure user-inputted data is validated and sanitized before storing it in
local storage or session storage to prevent security vulnerabilities like XSS.
Handle storage limitations: Be aware of storage size limits and data type limitations in local
storage and session storage, and implement strategies to handle these limitations, such as data
compression or alternative storage solutions.
When to Use session Storage
✅ Store temporary data that should be cleared when the tab or browser closes
✅ Hold form input data while a user fills a multi-step form
✅ Manage one-time messages like alerts or modals
✅ Track current tab, step, or view the user is interacting with
✅ Keep search filters or selections on a single-page app
✅ Prevent form resubmission after refresh
Security Considerations
❗ General Risks (Applies to Both)
⚠️No encryption : Data is stored as plain text and can be viewed using developer tools
⚠️Accessible by JavaScript : Any script on the page can access the data, including malicious
ones (if site is vulnerable)
⚠Susceptible to XSS (Cross-Site Scripting) attacks :If an attacker injects malicious
JavaScript, they can read or manipulate storage data