Web Tech Unit 2 Part2
Web Tech Unit 2 Part2
What is JavaScript?
JavaScript is a high-level, interpreted, object-oriented programming language primarily used for client-
side web development. It was created by Brendan Eich in 1995 at Netscape Communications.
Key Characteristics:
Dynamic Language: Variables and objects can be modified at runtime
Prototype-based: Objects can inherit directly from other objects
Loosely Typed: Variables don't need explicit type declarations
First-class Functions: Functions are objects and can be manipulated like any other object
Event-driven: Responds to user interactions and system events
Objects in JavaScript:
Definition:
Objects are collections of key-value pairs where keys are strings (properties) and values can be any
data type including functions (methods).
javascript
let student = {
name: "John",
age: 20,
grade: "A",
study: function() {
return this.name + " is studying";
}
};
2. Object Constructor:
javascript
3. Constructor Function:
javascript
Property Access:
Dot notation: object.property
Object Characteristics:
1. Object:
2. Array:
Key Methods:
Mutating: push() , pop() , shift() , unshift() , splice()
3. String:
Key Methods:
charAt() : Returns character at index
4. Number:
Key Methods:
toString() : Convert to string
5. Math:
Key Methods:
Math.round() , Math.floor() , Math.ceil() : Rounding
6. Date:
Key Methods:
getFullYear() , getMonth() , getDate() : Get components
7. Boolean:
8. Function:
Global Functions:
parseInt() : Parse string to integer
What is DOM?
The Document Object Model (DOM) is a platform and language-neutral interface that represents
HTML/XML documents as a tree structure of objects that can be manipulated with JavaScript.
DOM Structure:
Document: Root of the DOM tree
Document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── div
├── p
└── script
Key Methods:
getElementById() : Select element by ID
2. Element Object:
Key Methods:
getAttribute() , setAttribute() : Handle attributes
3. Window Object:
Key Methods:
alert() , confirm() , prompt() : User interaction
1. Navigator Object:
3. History Object:
4. Screen Object:
DOM Manipulation:
Selecting Elements:
javascript
// By ID
let element = document.getElementById("myId");
// By Class
let elements = document.getElementsByClassName("myClass");
// By Tag
let paragraphs = document.getElementsByTagName("p");
// CSS Selectors
let element = document.querySelector("#myId");
let elements = document.querySelectorAll(".myClass");
Modifying Elements:
javascript
// Change content
element.innerHTML = "<strong>Bold text</strong>";
element.textContent = "Plain text";
// Change attributes
element.setAttribute("src", "image.jpg");
element.id = "newId";
// Change styles
element.style.color = "red";
element.style.backgroundColor = "yellow";
javascript
// Create element
let newDiv = document.createElement("div");
newDiv.textContent = "New content";
// Add to document
document.body.appendChild(newDiv);
Event Handling:
Events are actions that occur in the browser (clicks, loads, etc.)
Common Events:
Form Object:
The form element is represented as a Form object in JavaScript with properties and methods for
manipulation.
Accessing Forms:
javascript
// By name attribute
let form = document.forms["formName"];
// By index
let form = document.forms[0];
// By ID
let form = document.getElementById("formId");
Form Properties:
elements: Collection of all form controls
Form Methods:
submit(): Submit form programmatically
Form Elements:
1. Input Elements:
Textarea: <textarea></textarea>
Select: <select><option></option></select>
Button: <button></button>
javascript
// Text input
let name = document.getElementById("nameInput").value;
// Checkbox
let isChecked = document.getElementById("checkbox").checked;
// Radio button
let radioValue = document.querySelector('input[name="gender"]:checked').value;
// Select dropdown
let selectedValue = document.getElementById("selectList").value;
Form Validation:
Purpose of Validation:
Ensure data quality and completeness
Provide immediate feedback to users
Types of Validation:
1. Client-Side Validation:
2. Server-Side Validation:
javascript
function validateRequired(field) {
return field.value.trim() !== "";
}
function validateEmail(email) {
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email.value);
}
function validateForm() {
let name = document.getElementById("name");
let email = document.getElementById("email");
let password = document.getElementById("password");
// Validate name
if (!validateRequired(name)) {
alert("Name is required");
name.focus();
return false;
}
// Validate email
if (!validateEmail(email)) {
alert("Please enter valid email");
email.focus();
return false;
}
// Validate password
if (!validateLength(password, 6)) {
alert("Password must be at least 6 characters");
password.focus();
return false;
}
return true;
}
Form Events:
Event Handling:
javascript
// Real-time validation
document.getElementById("email").addEventListener("blur", function() {
if (!validateEmail(this)) {
this.style.borderColor = "red";
} else {
this.style.borderColor = "green";
}
});
javascript
function isRequired(field) {
return field.value.trim() !== "";
}
2. Email Validation:
javascript
function isValidEmail(email) {
let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
return pattern.test(email);
}
javascript
function isValidPhone(phone) {
let pattern = /^\d{10}$/;
return pattern.test(phone);
}
4. Password Strength Validation:
javascript
function isStrongPassword(password) {
// At least 8 characters, one uppercase, one lowercase, one number
let pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/;
return pattern.test(password);
}
Can be bypassed