HTML, CSS, and JavaScript Roles
HTML (Content): Structures the web page.
CSS (Presentation): Styles the page (colors, layout, fonts).
JavaScript (Behavior): Adds interactivity and dynamic functionality.
What is JavaScript?
A client-side scripting language that runs in the browser.
Interpreted, not compiled.
Cannot directly:
Access hardware.
Interact with databases.
Can be disabled in browsers.
JavaScript History
1995: Introduced as LiveScript.
1996: Renamed JavaScript (Netscape 2, IE3 as JScript).
1997: Standardized as ECMAScript (ES1).
2009: ECMAScript 5 released.
2015: ECMAScript 6 introduced modern features (e.g., let , const , arrow
functions).
2022: Latest version: ECMA-262 (13th edition).
Development Requirements
Platforms: Mac, PC, Linux, UNIX.
Tools:
Text editors: Notepad++, Sublime Text, VS Code.
IDEs: Visual Studio, Xcode, Eclipse.
JavaScript Syntax
Case-Sensitive:
alert("text") is valid; Alert("text") is not.
Semicolons: End statements with ; (optional but recommended).
JS
alert("Hello"); alert("Welcome");
Spaces: Ignored by JavaScript.
JS
alert("Hello");
alert
("Hello");
Comments:
Single-line: // Comment
Multi-line: /* Multi-line comment */
Execution Order
JavaScript runs sequentially, top to bottom.
Placement:
In <head> : Runs before the body is loaded.
In <body> : Runs as the page content loads.
Here are the JavaScript Notes with the added explanation of the difference between
let , var , and const :
Where to Put JavaScript?
1. Separate File:
You can put JavaScript in a separate file. Example:
HTML
<script>
alert("Hello");
</script>
Or you can link to an external file:
HTML
<script src="myscript.js"></script>
2. Concretely:
Preferably placed at the end of the page: This ensures the HTML content is
loaded before the script is executed.
Script tag attributes:
HTML
<script src="myscript.js" type="text/javascript">
</script>
Other possible values for type attribute:
type="text/ecmascript"
type="application/javascript"
type="application/ecmascript"
Default: type="text/javascript"
Variables in JavaScript
1. Creating Variables:
To create a variable, use var , let , or const .
JS
var year;
var emailClient;
var dateDay;
var x;
Difference Between let , var , and const
2. var :
Scope: Function-scoped.
Hoisting: Variables declared with var are hoisted to the top of the function or
global scope and initialized with undefined .
Redeclaration: Can be redeclared in the same scope.
Example:
JS
var x = 10;
var x = 20; // Allowed (redeclaration)
3. let :
Scope: Block-scoped (limited to the block, statement, or expression where it's
defined).
Hoisting: Variables declared with let are hoisted, but not initialized until the
line of declaration (temporal dead zone).
Redeclaration: Cannot be redeclared in the same scope.
Example:
JS
let y = 10;
// let y = 20; // Error: Cannot redeclare block-scoped
variable 'y'
4. const :
Scope: Block-scoped (like let ).
Hoisting: Variables declared with const are hoisted, but not initialized until the
line of declaration (temporal dead zone).
Assignment: Cannot be reassigned after initialization, but objects and arrays
can be mutated.
Redeclaration: Cannot be redeclared in the same scope.
Example:
JS
const z = 30;
// z = 40; // Error: Assignment to constant variable
const obj = { name: "Alice" };
obj.name = "Bob"; // Allowed: Object properties can be
mutated
5. No Explicit Data Types:
Variables in JavaScript don't require a specific data type.
JS
var myVariable;
myVariable = 200; // Number
myVariable = "Hello"; // String
myVariable = true; // Boolean
myVariable = false; // Boolean
6. Case Sensitivity:
JavaScript is case-sensitive:
JS
var x = 200;
var X = 210; // This is a different variable
Conditions
JS
if (condition) {
// Code block if condition is true
} else {
// Code block if condition is false
}
condition ? 'right' : 'wrong'; // Ternary conditional
Operators and Expressions
1. Arithmetic Operators:
Use + , - , * , / , and % for arithmetic operations.
JS
result = 5 + 5 * 10;
result = (5 + 5) * 10;
2. Equality and Strict Equality:
== checks value equality.
=== checks both value and type equality.
JS
var a = 5, b = "5";
if (a == b) {
alert("equals");
}
3. Comparison Operators:
Compare values with operators like > , < , >= , <= , != , and !== .
JS
if (a > b) { ... }
if (a <= b) { ... }
4. Logical Operators:
Use && (AND) and || (OR) to combine conditions.
JS
if (a === b && c === d) { ... }
if (a > b || c < d) { ... }
5. Modulo Operator:
Find the remainder of a division with % .
JS
var year = 2023;
var rest = year % 3; // Remainder is 1
6. Increment / Decrement:
Use ++ to increment and -- to decrement a variable.
JS
a++; // Increment
a--; // Decrement
Console Methods
Useful for logging messages and debugging.
JS
console.log("message"); // General message or variable
console.info("message"); // Information message
console.warn("message"); // Warning message
console.error("message"); // Error message
Loops
1. while Loop:
Executes as long as the condition is true.
JS
let a = 1;
while (a < 10) {
console.log(a);
a++;
}
2. do...while Loop:
Executes at least once, then checks the condition.
JS
let a = 1;
do {
console.log(a);
a++;
} while (a < 10);
3. for Loop:
A more compact version of the loop, where the initialization, condition, and
increment are in one line.
JS
for (var i = 1; i < 10; i++) {
console.log(i);
}
4. break and continue :
break : Exits the loop immediately.
continue : Skips the current iteration and moves to the next one.
JS
for (var i = 1; i < 5000; i++) {
if (i == 101) {
break; // Exits the loop
}
}
for (var i = 1; i < 5000; i++) {
if (i % 5 == 0) {
continue; // Skips multiples of 5
}
}
Functions
1. Basic Function:
Functions allow you to encapsulate code for reuse.
JS
function myFunction() {
// Code here
}
myFunction(); // Calling the function
2. Function with Parameters:
You can pass values into functions via parameters.
JS
function myFunction(param1, param2) {
// Use param1 and param2
}
myFunction(10, 20); // Calling with arguments
3. Special Case (Extra/Undefined Arguments):
Functions can ignore extra arguments and return undefined for missing arguments.
JS
function calculation(code, month, interest, name) {
// Code here
}
calculation(145, 8, 4, "Omar Kamel"); // Correct
calculation(145, 8); // Missing arguments result in
`undefined`
Arrays (Tables)
Arrays allow storing multiple values in a single variable.
1. Creating Arrays:
JS
var valMultiple = [];
valMultiple[0] = 50;
valMultiple[1] = 60;
valMultiple[2] = "character";
// Or shorthand:
var valMultiple = [50, 60, "character"];
2. Array Constructors:
JS
var valMultiple = new Array(); // Empty array
var valMultiple = Array(5); // Array with 5 empty slots
Arrays – Properties and Methods
1. Length:
JS
var valMultiple = [10, 20, 30, 40, 50];
console.log(valMultiple.length); // 5
2. Reverse Array:
JS
var valMultipleInv = valMultiple.reverse();
3. Join Array into String:
JS
var string = valMultiple.join(); // "10,20,30,40,50"
DOM Interaction
To manipulate HTML elements with JavaScript:
JS
let myLinkArray = document.getElementsByTagName("a"); // Get
all links from the page
Numbers
1. Numeric Values:
JavaScript numbers are 64-bit floating-point numbers.
2. Addition vs. Concatenation:
JS
let a = 5, b = 5;
console.log(a + b); // 10 (Addition)
var a = "5", b = "5";
console.log(a + b); // "55" (Concatenation)
3. Handling Non-Numeric Strings:
JS
let a = "55";
var myNumber = Number(a); // Convert to number
if (isNaN(myNumber)) {
console.log("not a number");
}
Math Object
1. Math Methods:
Math.round(x) – Rounds a number to the nearest integer.
Math.max(a, b, c) – Returns the largest number.
Math.min(a, b, c) – Returns the smallest number.
Math.PI – Pi constant.
Math.random() – Returns a random number.
Math.sqrt() – Square root.
JS
var x = 200.6;
var y = Math.round(x); // 201
Strings
1. Defining Strings:
Can be enclosed in single ' or double " quotes.
JS
var phr = "javascript's friend";
2. String Methods:
Length: phr.length
To Uppercase/Lowercase: phr.toUpperCase() , phr.toLowerCase()
Split: phr.split(" ") (Splits string into an array)
Position: phr.indexOf("of") (Finds position of a substring)
Slice: phr.slice(2, 5) (Extracts part of the string)
3. String Comparison:
JS
var str1 = "Hello";
let str2 = "hello";
if (str1.toLowerCase() == str2.toLowerCase()) {
console.log("ok");
}
Dates
1. Creating Dates:
JS
var ajd = new Date(); // Current date and time
var d = new Date(2015, 0, 1); // January 1st, 2015 (months
start from 0)
2. Date Methods:
getMonth() – Returns the month (0 – 11).
getFullYear() – Returns the full year (YYYY).
getDate() – Returns the day of the month (1 – 31).
getHours() – Returns the hour (0 – 23).
getTime() – Returns milliseconds since Jan 1, 1970.
3. Date Comparison:
JS
var date1 = new Date(2015, 0, 1);
var date2 = new Date(2015, 0, 1);
if (date1.getTime() == date2.getTime()) {
console.log("Dates are equal");
}
Objects in JavaScript
Objects are containers for storing key-value pairs.
1. Creating Objects:
JS
var player = new Object();
player.name = "Omar";
player.score = 10000;
player.rank = 1;
// Or using object literal:
var player1 = { name: "Omar", score: 10000, rank: 1 };
2. Adding Methods to Objects:
JS
function ShowDetails() {
console.log(this.name + " is at rank " + this.rank);
}
player1.showDetails = ShowDetails;
player1.showDetails(); // Output: Omar is at rank 1
What is DOM?
Definition: A W3C standard that defines an interface for accessing and modifying
the structure, content, and style of HTML/XML documents.
Key Features:
Independent of programming language and platform.
Represents the document as a structured tree model.
Allows processing and updating content dynamically.
DOM Components
1. Document:
Represents a single web page (not the whole site).
Contains all the elements of the page.
2. Object:
Elements like tables, strings, images, etc., are objects.
Represents every element of the document.
3. Model:
A structured tree representation of the HTML page.
Simplifies complexity and abstracts the document structure.
Allows interaction with parents, children, or sibling elements.
Key Characteristics of DOM
Not a Programming Language: It is an idea and a standard for interacting with
documents.
JavaScript-Compatible: JavaScript uses DOM to manipulate web pages.
What Can We Do with DOM?
1. Access and modify elements:
Get the title text.
Update the CSS of a specific menu link ( display:none ).
2. Manipulate images and other elements dynamically:
Example: Move an image ( logo ) 40px to the right.
Nodes and Elements
1. Nodes:
Represent elements, attributes, text, and comments in the document.
2. Types of Nodes:
Node.ELEMENT_NODE: Represents elements like <div> , <li> .
Node.ATTRIBUTE_NODE: Represents attributes like id , class .
Node.TEXT_NODE: Represents text inside elements.
Accessing Elements
1. Using id :
JS
document.getElementById("someID");
Case-sensitive.
2. Using Tag Names:
JS
document.getElementsByTagName("li");
Returns a list of all <li> elements.
3. Access Nested Elements:
JS
var parent = document.getElementById("abc");
var children = parent.getElementsByTagName("li");
Modifying DOM
1. Change Attributes:
JS
myElement.getAttribute("align"); // Get attribute value
myElement.setAttribute("align", "left"); // Set attribute
value
2. Modify Content:
JS
element.innerHTML = "New content"; // Updates the content
of an element
3. Create Elements:
Create and Add a New Element:
JS
var newElement = document.createElement("li"); //
Create a new list item
newElement.innerHTML = "New Item"; // Set content
document.body.appendChild(newElement); // Append it to
the body
Create a Text Node:
JS
var textNode = document.createTextNode("Hello World");
newElement.appendChild(textNode); // Add the text node
to the element
4. Appending Elements:
JS
parentElement.appendChild(newElement); // Add new element
to parent
Events in Web Development
What is an Event?
An interaction or occurrence in a web page, triggered by user actions or browser
activities.
Examples of events:
Page reloads → onload event.
Mouse clicks → onclick event.
Typing on the keyboard → onkeypress , onkeydown events.
Mouse movement → onmousemove event.
Page scrolling → onscroll event.
Event Names
Events are prefixed with on , e.g.,:
onload → Triggered when the page fully loads.
onclick → Triggered on a mouse click.
onfocus → Triggered when an input field is focused.
onblur → Triggered when an input field loses focus.
Events are managed through event listeners.
Methods to Handle Events
1. Inline HTML Event Handling
Add JavaScript directly into the HTML element.
Example:
HTML
<button onclick="alert('Hello!');">Click Me</button>
Advantages:
Simple for basic actions.
Disadvantages:
Difficult to maintain for large projects.
Violates the separation of HTML and JavaScript.
2. Element Property Event Handling
Assign a function to an element’s event property.
Example:
HTML
<button id="myButton">Click Me</button>
<script>
var button = document.getElementById("myButton");
button.onclick = function () {
alert("Hello!");
};
</script>
Key Points:
Commonly used for moderate-sized applications.
Event properties include onclick , onblur , onload , etc.
3. Using Event Listeners
A modern approach that allows multiple handlers for the same event.
Syntax:
JS
element.addEventListener(eventType, callbackFunction,
useCapture);
Parameters:
eventType : Type of the event (e.g., 'click' , 'keydown' ).
callbackFunction : Function to execute when the event triggers.
useCapture : Optional; defines event propagation behavior. Default is false
(bubbling).
Example:
HTML
<button id="myButton">Click Me</button>
<script>
var button = document.getElementById("myButton");
button.addEventListener("click", function () {
alert("Hello from Event Listener!");
});
</script>
Remove Event Listener:
JS
button.removeEventListener("click", callbackFunction);
Advantages:
Cleaner and more maintainable code.
Supports multiple handlers for a single event.
Handling Events in Older Browsers (IE8 and Below)
Use attachEvent instead of addEventListener :
JS
document.attachEvent('onclick', function () {
alert('Hello from IE8!');
});
Remove events using detachEvent :
JS
document.detachEvent('onclick', function);
Comparison of Event Handling Methods
Method Description Use Case
Inline HTML JavaScript directly in HTML. Quick, small scripts, not
Event scalable.
Element Property Use event properties like onclick . Moderate-sized scripts,
Events better separation.
Event Listeners Use addEventListener() for Scalable, modern web
better control. applications.
JavaScript Form Validation
1. Fetching Inputs
Code Example:
JS
let Name = document.querySelector("#Name"),
User_Name = document.querySelector("#User_Name"),
Password = document.querySelector("#Password"),
Confirm_Password =
document.querySelector("#Confirm_Password"),
Birthdate = document.querySelector("#Birthdate"),
Email = document.querySelector("#Email"),
Phone_Number = document.querySelector("#Phone_Number"),
Submit_Btn = document.querySelector("#Submit_Btn"),
small = document.querySelector("small");
Fetch all input fields, the submit button, and the small tag to show error messages.
2. Submit Button Event
Purpose:
Prevent the default behavior (form submission to server).
Call a function ( checkInputs() ) to validate inputs.
Code Example:
JS
Submit_Btn.addEventListener("click", (event) => {
event.preventDefault();
checkInputs();
});
3. Retrieve Input Values
Use .value.trim() to get and clean the input values by removing leading/trailing
spaces.
Code Example:
JS
const NameValue = Name.value.trim();
const EmailValue = Email.value.trim();
4. Input Validation
General Structure:
Check each input.
If invalid: Call setErrorFor() (show error message and mark input as invalid).
If valid: Call setSuccessFor() (mark input as valid).
Example for Name Field:
JS
if (NameValue === "") {
setErrorFor(Name, "Name cannot be blank");
} else {
setSuccessFor(Name);
}
5. Functions for Error and Success
Purpose:
Show error/success styles and messages.
Implementation:
JS
function setErrorFor(input, message) {
small.innerText += "\n" + message;
input.className += " error";
}
function setSuccessFor(input) {
input.className += " success";
}
CSS Classes:
CSS
.error {
color: red;
background-color: rgb(255 0 0 / 0.1);
border: 1px solid red;
}
.success {
color: green;
background-color: rgb(0 255 0 / 0.1);
border: 1px solid green;
}
6. Validating Email and Phone
Regular Expressions:
Email: /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]
{2,5})$/
Phone: /^([0]{1}[5-7]{1}[0-9]{8})$/
Functions:
JS
function isEmail(Email) {
return /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-
zA-Z]{2,5})$/.test(Email);
}
function isPhone_Number(Phone_Number) {
return /^([0]{1}[5-7]{1}[0-9]{8})$/.test(Phone_Number);
}
Validation Example:
JS
if (EmailValue === "") {
setErrorFor(Email, "Email cannot be blank");
} else if (!isEmail(EmailValue)) {
setErrorFor(Email, "Email is not valid");
} else {
setSuccessFor(Email);
}
7. Key Methods
.trim() : Removes leading/trailing spaces.
.test() : Validates input against a regular expression.
BY Habiba.