0% found this document useful (0 votes)
16 views13 pages

JavaScript Part 3

Uploaded by

vedantmp6710
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views13 pages

JavaScript Part 3

Uploaded by

vedantmp6710
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

JavaScript Validation:

Definition

JavaScript validation is the process of using JavaScript code to check the input data submitted
through web forms before it is sent to the server. It ensures that the data entered by the user
meets certain criteria, such as correct format, required fields being filled, or values being within
a specified range.

About JavaScript Validation

 Purpose:
The main goal of JavaScript validation is to catch errors or invalid inputs on the client
side (in the user's browser) before sending data to the server. This reduces server load
and improves user experience by providing instant feedback.

 Types of Validation:

o Required field validation: Check if a field is not empty.

o Format validation: Verify if the input matches a pattern (e.g., email, phone
number).

o Range validation: Ensure numbers are within a certain range.

o Length validation: Check if the input length is within limits.

o Custom validation: Any other specific rules based on application needs.

 How it works:
JavaScript validation is often done by attaching event listeners to form submission or
input fields. When the user submits a form, the JavaScript function runs, checks the
data, and either allows the form submission or shows error messages.

 Advantages:

o Faster feedback for users without waiting for server response.

o Reduces unnecessary server requests.

o Helps prevent incorrect data from being submitted.

 Limitations:

o JavaScript can be disabled on the client side, so validation should also be done
on the server side for security.

o It cannot fully protect against malicious input.

Simple Example

<form onsubmit="return validateForm()">

Email: <input type="text" id="email" name="email">

<input type="submit" value="Submit">


</form>

<script>

function validateForm() {

const email = document.getElementById('email').value;

if (email === "") {

alert("Email must be filled out");

return false; // Prevent form submission

// Basic email format check

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailPattern.test(email)) {

alert("Please enter a valid email address.");

return false;

return true; // Allow form submission

</script>
JavaScript Regular Expression:
Definition

A regular expression (or regex) in JavaScript is a sequence of characters that defines a search
pattern. It is mainly used for pattern matching within strings — such as searching, replacing,
or validating text.

About JavaScript Regular Expressions

 Purpose:
Regular expressions allow you to perform complex pattern-based searches and
manipulations on strings efficiently. They are very useful for validating input, parsing
text, or performing find-and-replace operations.

 Syntax:
In JavaScript, regular expressions can be created in two ways:

1. Literal notation:

2. const regex = /pattern/flags;

3. Constructor function:

4. const regex = new RegExp("pattern", "flags");

 Components of a Regular Expression:

o Literals: Match exact characters (e.g., /cat/ matches "cat").

o Metacharacters: Special characters with special meanings (e.g., . matches any


character, \d matches any digit).

o Quantifiers: Specify how many times something can appear (e.g., * zero or
more, + one or more).

o Anchors: Define position in string (e.g., ^ for start, $ for end).

o Character classes: Define sets of characters (e.g., [a-z] for lowercase letters).

 Flags:
These modify the behavior of the regex:

o g – global search (find all matches, not just first)

o i – case-insensitive search

o m – multi-line search

 Usage in JavaScript:

o test() — checks if a pattern exists in a string, returns true or false.

o exec() — executes a search and returns matched information.

o String methods using regex: match(), replace(), search(), split().


Example: Simple Email Validation

const email = "[email protected]";

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (emailRegex.test(email)) {

console.log("Valid email!");

} else {

console.log("Invalid email.");

Summary

 Regular expressions are powerful tools for pattern matching in strings.

 They can be used to validate input, search, replace, and split strings.

 Understanding regex syntax and patterns unlocks a lot of text-processing capabilities in


JavaScript.
JavaScript Event:
Definition

An event in JavaScript is an action or occurrence that happens in the system you are
programming, which the system tells you about so your code can respond to it. These actions
can be user interactions like clicks, key presses, mouse movements, or system-generated
events like page loading.

About JavaScript Events

 Purpose:
Events allow your web page to be interactive and dynamic. Instead of the page being
static, you can run JavaScript code in response to user actions or changes in the
browser.

 Common types of events:

o Mouse events: click, dblclick, mouseover, mouseout, mousedown, mouseup

o Keyboard events: keydown, keyup, keypress

o Form events: submit, change, focus, blur

o Window events: load, resize, scroll

o Touch events: for touch devices like smartphones and tablets

 Event handling:
You can listen for events on elements and then run functions (called event handlers or
listeners) when those events happen.

How to Attach Event Listeners

1. Using HTML attributes (inline event handlers):

<button onclick="alert('Button clicked!')">Click Me</button>

2. Using JavaScript's addEventListener:

const btn = document.getElementById('myButton');

btn.addEventListener('click', function() {

alert('Button clicked!');

});

Event Object

When an event occurs, the browser often passes an event object to the event handler function.
This object contains details about the event, like:

 Which element triggered the event (event.target)

 Mouse position (event.clientX, event.clientY)


 Which key was pressed (event.key, event.keyCode)

 And more...

Example:

document.addEventListener('click', function(event) {

console.log('Clicked element:', event.target);

});

Event Propagation

Events in JavaScript have a flow:

 Capturing phase: Event goes down from the window to the target element.

 Target phase: Event reaches the target element.

 Bubbling phase: Event bubbles up from the target element to the window.

By default, event listeners listen during the bubbling phase, but you can specify if you want to
listen during capturing.

Summary

 Events are actions or occurrences like clicks, typing, or loading.

 JavaScript can respond to these events using event handlers.

 Event listeners can be attached in various ways.

 The event object provides details about the event.

 Event propagation determines how events move through the DOM.


JavaScript DOM:
Definition

DOM stands for Document Object Model. It is a programming interface for HTML and XML
documents. The DOM represents the page so that programs (like JavaScript) can change the
document structure, style, and content dynamically.

In simpler terms:
The DOM is a tree-like structure where every element, attribute, and piece of text in an HTML
document is represented as a node. JavaScript can interact with these nodes to manipulate the
web page.

About JavaScript DOM

 Purpose:
The DOM allows JavaScript to access and manipulate HTML elements on a web page
after the page has loaded. This enables dynamic changes like adding/removing content,
changing styles, handling events, and more.

 How the DOM works:


When a web page loads, the browser creates a DOM tree based on the HTML structure.
JavaScript can then traverse this tree and update elements on the fly.

 DOM Nodes:

o Element nodes: Represent HTML elements (e.g., <div>, <p>, <a>).

o Text nodes: The actual text inside elements.

o Attribute nodes: Attributes of elements (e.g., class, id).

 Common DOM Manipulation:

o Selecting elements: Using methods like getElementById,


getElementsByClassName, querySelector, etc.

o Changing content: Modify innerHTML, textContent.

o Changing styles: Modify style properties.

o Adding/removing elements: Using methods like appendChild, removeChild.

o Handling events: Attach event listeners to elements.

Example: Changing Text of a Paragraph

<p id="myPara">Hello World!</p>

<button onclick="changeText()">Change Text</button>

<script>

function changeText() {
const para = document.getElementById('myPara');

para.textContent = "Text changed by JavaScript!";

</script>

Summary

 The DOM is a structured representation of the HTML document.

 JavaScript uses the DOM to interact with and manipulate the webpage dynamically.

 This interaction makes web pages interactive and responsive to user actions.

1. Types / Levels of DOM

Historically, the DOM specification evolved through different levels to standardize how
browsers implement DOM APIs:

 DOM Level 0:
The earliest, informal model. Mostly browser-specific and included basic access to
elements (like document.all) and simple event handling.

 DOM Level 1:
Introduced the core DOM structure (element trees, nodes), and basic methods for
accessing and manipulating the document (getElementById, getElementsByTagName,
etc).

 DOM Level 2:
Added support for events (event listeners), CSS manipulation, and traversal
enhancements.

 DOM Level 3:
Added support for keyboard events, XPath, and better loading and saving of documents.

2. DOM Node Types

The DOM represents an HTML/XML document as a tree of nodes, and nodes can be of different
types. Here are the main DOM node types:

Node Type
Node Type Name Description
Number

1 Element Node Represents an HTML element (e.g., <div>, <p>)

Represents an attribute of an element (e.g., class, id)


2 Attribute Node (mostly obsolete, attributes are accessed as properties
now)
Node Type
Node Type Name Description
Number

3 Text Node The actual text inside an element or attribute

CDATA Section
4 Used in XML to include blocks of text without parsing
Node

Processing
7 Instructions for XML processors
Instruction Node

8 Comment Node Represents comments in the code (<!-- comment -->)

9 Document Node The entire document (root of the DOM tree)

Document Type
10 Represents the document type declaration (<!DOCTYPE>)
Node

Document A lightweight container used to hold and manipulate parts


11
Fragment Node of the DOM

3. Examples in JavaScript

To check the node type of a DOM element:

const element = document.getElementById('myDiv');

console.log(element.nodeType); // Outputs: 1 (Element Node)

const text = element.firstChild;

console.log(text.nodeType); // Outputs: 3 (Text Node)

Summary

 Types of DOM can mean the DOM Levels (evolution of standards) or DOM Node Types
(different kinds of nodes in the document tree).

 Most common node types are Element (1), Text (3), and Document (9).

 Understanding node types is useful for traversing and manipulating the DOM effectively.
JavaScript Cookie:

Definition

A cookie is a small piece of data stored on the user’s browser by a website. In JavaScript,
cookies are used to store and retrieve data about the user or session directly on their device,
enabling websites to remember information between page loads or visits.

About JavaScript Cookies

 Purpose:
Cookies allow websites to remember user-specific information such as login status,
preferences, shopping cart contents, or tracking identifiers.

 How cookies work:


When a website sends a cookie, the browser stores it and sends it back to the server
with every subsequent request to the same website. This helps maintain state across
multiple page visits.

 Setting cookies in JavaScript:


You can create or update cookies by assigning a specially formatted string to
document.cookie.

 Reading cookies in JavaScript:


Cookies are accessed as a single string from document.cookie. You typically need to
parse this string to get individual cookie values.

 Cookie attributes:
Cookies can have optional attributes such as:

o expires or max-age (to set expiration time)

o path (scope within the website)

o domain (which domain the cookie belongs to)

o secure (cookie sent only over HTTPS)

o HttpOnly (not accessible via JavaScript, for security)

 Limitations:

o Cookies are limited in size (~4KB per cookie).

o Browsers limit the number of cookies per domain (usually around 20-50).

o Cookies are sent with every HTTP request, so too many cookies can slow down
the site.

Example: Setting, Getting, and Deleting Cookies

// Set a cookie (expires in 7 days)

document.cookie = "username=JohnDoe; max-age=" + 7*24*60*60 + "; path=/";


// Read cookies

console.log(document.cookie); // Output: "username=JohnDoe"

// Function to get a specific cookie value

function getCookie(name) {

const cookies = document.cookie.split('; ');

for (const cookie of cookies) {

const [key, value] = cookie.split('=');

if (key === name) return value;

return null;

console.log(getCookie('username')); // Output: JohnDoe

// Delete a cookie by setting its expiry date to past

document.cookie = "username=; max-age=0; path=/";

Summary

 Cookies are small data pieces stored on the browser.

 JavaScript can create, read, and delete cookies using document.cookie.

 Cookies help websites remember user info across sessions.

 Use cookies wisely because of size and security limitations.


JavaScript Cookie:

Definition

A cookie is a small piece of data stored on the user’s browser by a website. In JavaScript,
cookies are used to store and retrieve data about the user or session directly on their device,
enabling websites to remember information between page loads or visits.

About JavaScript Cookies

 Purpose:
Cookies allow websites to remember user-specific information such as login status,
preferences, shopping cart contents, or tracking identifiers.

 How cookies work:


When a website sends a cookie, the browser stores it and sends it back to the server
with every subsequent request to the same website. This helps maintain state across
multiple page visits.

 Setting cookies in JavaScript:


You can create or update cookies by assigning a specially formatted string to
document.cookie.

 Reading cookies in JavaScript:


Cookies are accessed as a single string from document.cookie. You typically need to
parse this string to get individual cookie values.

 Cookie attributes:
Cookies can have optional attributes such as:

o expires or max-age (to set expiration time)

o path (scope within the website)

o domain (which domain the cookie belongs to)

o secure (cookie sent only over HTTPS)

o HttpOnly (not accessible via JavaScript, for security)

 Limitations:

o Cookies are limited in size (~4KB per cookie).

o Browsers limit the number of cookies per domain (usually around 20-50).

o Cookies are sent with every HTTP request, so too many cookies can slow down
the site.

Example: Setting, Getting, and Deleting Cookies

// Set a cookie (expires in 7 days)

document.cookie = "username=JohnDoe; max-age=" + 7*24*60*60 + "; path=/";


// Read cookies

console.log(document.cookie); // Output: "username=JohnDoe"

// Function to get a specific cookie value

function getCookie(name) {

const cookies = document.cookie.split('; ');

for (const cookie of cookies) {

const [key, value] = cookie.split('=');

if (key === name) return value;

return null;

console.log(getCookie('username')); // Output: JohnDoe

// Delete a cookie by setting its expiry date to past

document.cookie = "username=; max-age=0; path=/";

Summary

 Cookies are small data pieces stored on the browser.

 JavaScript can create, read, and delete cookies using document.cookie.

 Cookies help websites remember user info across sessions.

 Use cookies wisely because of size and security limitations.

You might also like