JavaScript Fundamentals and DOM Manipulation
calculator.js
let string = "";
let buttons = document.querySelectorAll('.button');
let inputBox = document.getElementById('inputBox');
let outputBox = document.getElementById('outputBox');
Array.from(buttons).forEach((button) => {
button.addEventListener('click', (e) => {
if (e.target.innerHTML == '=') {
try {
string = eval(string);
outputBox.value = string;
} catch (error) {
outputBox.value = "Error";
}
} else if (e.target.innerHTML == 'C') {
string = "";
inputBox.value = "";
outputBox.value = "";
} else {
string += e.target.innerHTML;
inputBox.value = string;
}
});
});
From.js
const email = document.getElementById("emailInput");
const fname = document.getElementById("fname");
const lname = document.getElementById("lname");
const phone = document.getElementById("phone");
const pass = document.getElementById("password");
const confirmPass = document.getElementById("confirmPassword");
email.addEventListener("input", () => validateForm("email") )
fname.addEventListener("input", () => validateForm("fname"));
lname.addEventListener("input", () => validateForm("lname"));
phone.addEventListener("input", () => validateForm("phone"));
pass.addEventListener("input", () => validateForm("pass"));
confirmPass.addEventListener("input", () => validateForm("confirmPass"));
function removeErrorMessage(element) {
const nextElement = element.nextElementSibling;
if (nextElement && nextElement.tagName === 'P' && nextElement.style.color === 'red') {
nextElement.remove()
}
}
function addErrorMessage(element, message) {
removeErrorMessage(element);
const errorMsg = <p style='color:red;'>${message}</p>;
element.insertAdjacentHTML("afterend", errorMsg);
}
/*
?= is look ahead expression it means, that character needs to be in the string but don't need to follow any order specifically
*/
function validateForm(toValidate) {
let isValid = true;
const nameRegEx = /^[A-Za-z]{2,30}$/;
const passwordRegEx = /((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,20})/;
const emailRegEx = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
const phoneRegEx= /(^([0-9]{10})$)|(^[+]{1})([0-9]{11,13})|(^[0]{2})([0-9]{11,13}$)/;
if (toValidate === "all" || toValidate === "email") {
removeErrorMessage(email);
if (email.value.trim() === "") {
isValid = false;
addErrorMessage(email, "Email is required");
} else if (!emailRegEx.test(email.value.trim())) {
isValid = false;
addErrorMessage(email, "Invalid Email Format");
}
}
if (toValidate === "all" || toValidate === "fname") {
removeErrorMessage(fname);
if (fname.value.trim() === "") {
isValid = false;
addErrorMessage(fname, "First Name is required");
} else if (!nameRegEx.test(fname.value.trim())) {
isValid = false;
addErrorMessage(fname, "Invalid First Name format");
}
}
if (toValidate === "all" || toValidate === "lname") {
removeErrorMessage(lname);
if (lname.value.trim() === "") {
isValid = false;
addErrorMessage(lname, "Last Name is required");
} else if (!nameRegEx.test(lname.value.trim())) {
isValid = false;
addErrorMessage(lname, "Invalid Last Name format");
}
}
if(toValidate ==="all" || toValidate==="phone"){
removeErrorMessage(phone);
if(phone.value.trim()===""){
isValid= false;
addErrorMessage(phone, "Phone Number is required");
}else if (!phoneRegEx.test(phone.value.trim())){
isValid=false;
addErrorMessage(phone, "Invalid Phone Number format");
}}
if (toValidate === "all" || toValidate === "pass") {
removeErrorMessage(pass);
if (pass.value.trim() === "") {
isValid = false;
addErrorMessage(pass, "Password is required");
} else if (!passwordRegEx.test(pass.value)) {
isValid = false;
addErrorMessage(pass, "Password must be at least 8 characters long containing both uppercase and lowercase and contain at least one letter and one number");
}
}
if (toValidate === "all" || toValidate === "confirmPass") {
removeErrorMessage(confirmPass);
if (confirmPass.value.trim() === "") {
isValid = false;
addErrorMessage(confirmPass, "Confirm Password is required");
} else if (confirmPass.value !== pass.value) {
isValid = false;
addErrorMessage(confirmPass, "Passwords do not match");
}
}
return isValid;
}
clock.js
function clock (){
const time = new Date();
let hour = time.getHours();
let min = time.getMinutes();
let sec = time.getSeconds();
hour = checkDigit(hour);
min = checkDigit(min);
sec = checkDigit(sec);
const finalTime = `${hour}:${min}:${sec}`;
const element = document.getElementById("time");
element.innerHTML = finalTime;
}
const interval = setInterval(() => {
clock();
return () => clearInterval(interval);
}, 1000);
function checkDigit (value) {
if (value > 0 && value < 10) {
return `0${value}`;
}
return value;
}
Document Object Model (DOM)
Concept and Structure
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the document as a tree structure, enabling scripts to interact with and update the content dynamically.
Document as a Tree
- Represents HTML as a hierarchical tree.
- Each element is a node with parent-child relationships.
- Example:
<html>
<body>
<h1>Title</h1>
<p>Some text</p>
</body>
</html>
DOM Tree:
– Document
– html
– body
– h1
– p - Nodes:
- Element nodes (e.g.,
<div>
) - Attribute nodes (e.g.,
id
) - Text nodes
- Element nodes (e.g.,
- DOM Methods (e.g.,
getElementById
,querySelector
)
Importance
- Dynamic content manipulation
- Event handling
- Separation of concerns (HTML and JavaScript)
- Platform independence
setTimeout()
Executes a function after a specified delay (milliseconds).
Purpose
- Delay execution without blocking.
- Asynchronous behavior.
Syntax
setTimeout(function, delay);
Example
setTimeout(() => { console.log("Hello after 3 seconds!"); }, 3000);
Usage
- Timed messages/alerts
- Delayed animations
- Form validation/API calls
Regular Expressions
Powerful for pattern matching and text manipulation.
Significance
- Efficient pattern matching
- Text manipulation/parsing
- Input validation
- Simplification of complex operations
- Cross-platform support