JavascriptPracticalFileakash
JavascriptPracticalFileakash
CT University, Ludhiana
Submitted in partial fulfilment of the requirement for the award of the Degree
of Bachelors of Data Science and Artificial Intelligence in Computer Science
Engineering along with IBM.
SUBMITTED BY: SUBMITTED TO:
NAME: AKASHDEEP SINGH MS. PARUL
REGISTRATION NO.: 72212236
1|Page
TABLE OF CONTENTS
2|Page
Practical 1
Program to implement Hello using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Program to implement Hello using JavaScript</h1>
<p id="output"></p>
</body>
<script>
document.write("Hello");
document.getElementById("output").innerHTML = "Hello";
</script>
</html>
Output:
3|Page
Practical 2
Program to implement various Operators using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Operators</title>
</head>
<body>
<h1>JS Operators</h1>
<h3>Arithmetic Operators</h3>
<h4> Let two numbers be 10 and 5 the arithmetic operations performed on them are as follows: </h4>
<h5>Addition</h5>
<p id="add"></p>
<h5>Subtraction</h5>
<p id="sub"></p>
<h5>Multiplication</h5>
<p id="mul"></p>
<h5>division</h5>
<p id="div"></p>
<h5>Modulus </h5>
<p id="mod"></p>
<h3>logical Operators</h3>
<h4> Let two numbers be 10 and 156 the Logical operations performed on them are as follows: </h4>
<h5>AND</h5>
<p>((x>y) && x )</p>
<p id="and"></p>
<h5>OR</h5>
<p>((x>y) || x )</p>
<p id="or"></p>
<h5>NOT</h5>
<p>!x</p>
<p id="not"></p>
<h3>Assignment Operators</h3>
<h5>Assignment</h5>
<p>
c=d
</p>
<p id="assign"></p>
<h5>Increment </h5>
<p> c+=5 </p>
<p id="increment"></p>
<h5>Left Shift </h5>
<p> 4>>1</p>
<p id="left"></p>
<h5>Right Shift </h5>
<p> 4<<1 </p>
<p id="right"></p>
<h3>Comparison Operators</h3>
<h5>gREATER THEN</h5>
<p>4>1</p>
<p id="greater"></p>
<h5>Less Than</h5>
4|Page
<p>4<1</p>
<p id="less"></p>
<h5>Equal to</h5>
<p>4==1</p>
<p id="equal"></p>
<h5>Not equal to</h5>
<p>4!=1</p>
<p id="notequal">
</p>
<h5>Greater Then equal to</h5>
<p>4>=1</p>
<p id="great"></p>
<h5>Less than Equal to</h5>
<p>4<=1</p>
<p id="lessequal"></p>
</body>
<script>
//Arithmetic Operators
let a = 10;
let b = 5;
document.getElementById("add").innerHTML = a + b;
document.getElementById("sub").innerHTML = a - b;
document.getElementById("mul").innerHTML = a * b;
document.getElementById("div").innerHTML = a / b;
document.getElementById("mod").innerHTML = a % b;
//logical operators
let x = 10;
let y = 156
document.getElementById("and").innerHTML = ((x>y) && x )
document.getElementById("and").innerHTML = ((x>y) || x )
document.getElementById("not").innerHTML = !x
//Assignment Operators
let c = 10;
let d = 5;
document.getElementById("assign").innerHTML = c = d;
document.getElementById("increment").innerHTML = c+=5 ;
document.getElementById("left").innerHTML = 4>>1 ;
document.getElementById("right").innerHTML = 4<<1 ;
//Comparison Operators
document.getElementById("greater").innerHTML = 4>1 ;
document.getElementById("less").innerHTML = 4<1 ;
document.getElementById("equal").innerHTML = 4==1 ;
document.getElementById("notequal").innerHTML = 4!=1 ;
document.getElementById("great").innerHTML = 4>=1 ;
document.getElementById("lessequal").innerHTML = 4<=1 ;
</script>
</html>
5|Page
Output:
6|Page
Practical 3
Program to implement Conditional Operators using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- conditional operators -->
<h1>Conditional Operators in Javascript</h1>
<h4>Ternary Operator</h4>
<!-- Expression 1? Expression 2: Expression 3 -->
<p id="ternary"></p>
<h4>Logical And (&&)</h4>
<p id="logicalAnd"></p>
<h4>Logical Or(||)</h4>
<p id="logicalOr"></p>
<h4>Logical Not (!) </h4>
<p id="logicalNot"></p>
<h4>Using Ternary Operator in a Function</h4>
<p id="grade"></p>
</body>
<script>
// ternary operator
let age = 20;
let canVote = (age>=18) ? "Yes , can vote ": "No , cannot vote ";
document.getElementById("ternary").textContent = "Ternary operator: " + canVote;
// Logical Operator
let hasId = true;
let hasRegistered = true;
let eligibility = (hasId && hasRegistered)? "Yes eligible" : "Not eligible";
document.getElementById("logicalAnd").textContent = "Logical And: " + eligibility;
// Logical OR
let isHoliday = false;
let isWeekend = true;
let relaxation = (isHoliday || isWeekend) ? "You can relax" : "You cant relax";
document.getElementById("logicalOr").innerText = "Logical OR: " + relaxation;
7|Page
document.getElementById("grade").textContent = `using Function in Ternary Operator : The Grade for a
score of ${score} is ${grade} `;
</script>
</html>
Output:
8|Page
Practical 4
Program to Implement If-Else Statement using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-Else Statements in Javascript
</title>
</head>
<body>
<h2>Check if number is positive , negative or zero</h2>
<label for="number">Enter a number: </label>
<input type="number" placeholder="Enter a number:" id="number">
<button onCLick="checkNumber()">Check</button>
<p id="result"></p>
<script>
function checkNumber() {
// get input value
let number = document.getElementById("number").value;
Output:
9|Page
Practical 5
Program to illustrate the Loops (For, while, do-while) in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Loops Example</h1>
<h4>For loop Output: </h4>
<p id="for-loop"></p>
<h4>While loop Output: </h4>
<p id="while-loop"></p>
<h4>Do While loop Output: </h4>
<p id="do-while-loop"></p>
</body>
<script>
// For Loop
let forLoopOutput = "";
for(let i = 1; i <=5 ; i++){
forLoopOutput += "Iteration: " + i + "<br>";
}
document.getElementById("for-loop").innerHTML = forLoopOutput;
// while loop
let whileLoopOutput = "";
let j = 1;
while(j <= 5){
whileLoopOutput += "Iteration: " + j + "<br>";
j++;
}
document.getElementById("while-loop").innerHTML = whileLoopOutput;
// Do While Output
let doWhileLoopOutput = "";
let k = 1;
do{
doWhileLoopOutput += "Iteration: " + k + "<br>";
k++;
}while(k <= 5);
document.getElementById("do-while-loop").innerHTML = doWhileLoopOutput;
</script>
</html>
10 | P a g e
Output:
11 | P a g e
Practical 6
Program to illustrate the usage of Functions in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions with User Input</title>
</head>
<body>
<script>
// Function to calculate the area of a rectangle with user input
function calculateArea() {
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
if(length && width) {
var area = length * width;
document.getElementById("area").innerHTML = "The area of the rectangle is: " + area + " square
units.";
} else {
document.getElementById("area").innerHTML = "Please enter valid values for length and width.";
}
}
12 | P a g e
</body>
</html>
Output:
13 | P a g e
Practical 7
Program to illustrate the usage of Events in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Event Example</title>
</head>
<body>
<h2>JavaScript Events Example</h2>
<button id="myButton">Click Me!</button>
<p id="message"></p>
<script>
// Select the button element by its ID
const button = document.getElementById("myButton");
const messageParagraph = document.getElementById("message");
Output:
14 | P a g e
Practical 8
Program to illustrate the usage of Cookies in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Example</title>
</head>
<body>
<p id="output"></p>
<script>
// Function to set a cookie
function setCookie() {
const name = document.getElementById("cookieName").value;
const value = document.getElementById("cookieValue").value;
const days = 7; // Cookie expires in 7 days
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
document.getElementById("output").textContent = `Cookie "${name}" set!`;
}
15 | P a g e
function deleteCookie() {
const name = document.getElementById("cookieName").value;
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
document.getElementById("output").textContent = `Cookie "${name}" deleted!`;
}
</script>
</body>
</html>
Output:
16 | P a g e
Practical 9
Program to illustrate the Page direction in JavaScript
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
<title>Page Redirection Example</title>
</head>
<body>
<script>
// Function to redirect to a specific page
function redirectToPage() {
window.location.href = “https://www.google.com”; // Redirects to Google
}
</body>
</html>
Output:
17 | P a g e
Practical 10
Program to illustrate the Dialog Boxes in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dialog Boxes Example</title>
</head>
<body>
<p id="output"></p>
<script>
// Function to display an alert dialog
function showAlert() {
alert("This is an alert box!");
}
</body>
</html>
18 | P a g e
Output:
19 | P a g e
Practical 11
Program to Illustrate the Page Printing in JavaScript
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
<title>Page Printing Example</title>
</head>
<body>
<script>
// Function to open the print dialog
function printPage() {
window.print(); // Triggers the browser’s print dialog
}
</script>
</body>
</html>
Output:
20 | P a g e
Practical 12
Program to Implement Error Handling in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error Handling Example</title>
</head>
<body>
<p id="output"></p>
<script>
// Function to process input and handle errors
function processInput() {
const output = document.getElementById("output");
output.textContent = ""; // Clear previous output
try {
const input = document.getElementById("numberInput").value;
if (input === "") throw "Input is empty";
if (isNaN(input)) throw "Not a valid number";
</body>
</html>
21 | P a g e
Output:
22 | P a g e
Practical 13
Program to Implement form validation using JavaScript to ensure
input correctness (e.g., email validation, password strength)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
<style>
.error { color: red; }
.success { color: green; }
</style>
</head>
<body>
<h1>Form Validation in JavaScript</h1>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="email">Email:</label>
<input type="text" id="email" name="email" placeholder="Enter your email">
<p id="emailError" class="error"></p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your password">
<p id="passwordError" class="error"></p>
<button type="submit">Register</button>
<p id="formOutput"></p>
</form>
<script>
// Function to validate the form inputs
function validateForm() {
let isValid = true; // Flag to track if the form is valid
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
const emailError = document.getElementById("emailError");
const passwordError = document.getElementById("passwordError");
const formOutput = document.getElementById("formOutput");
emailError.textContent = "";
passwordError.textContent = "";
formOutput.textContent = "";
// Email validation: checks if email format is valid
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
emailError.textContent = "Please enter a valid email address.";
isValid = false;
}
// Password validation: minimum 8 characters, at least one uppercase, one lowercase, one digit, and one
special character
const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
if (!passwordPattern.test(password)) {
passwordError.textContent = "Password must be at least 8 characters long, with an uppercase letter, a
lowercase letter, a number, and a special character.";
isValid = false;
}
23 | P a g e
if (isValid) {
formOutput.textContent = "Form submitted successfully!";
formOutput.classList.add("success");
} else {
formOutput.textContent = "Please fix the errors above and try again.";
formOutput.classList.remove("success");
}
Output:
24 | P a g e
Practical 14
Program to illustrate the usage of Animation & Multimedia in
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animation & Multimedia in JavaScript</title>
<style>
/* Styling for the animated box */
#animatedBox {
width: 50px;
height: 50px;
background-color: dodgerblue;
position: absolute;
top: 50px;
left: 0;
}
/* Container styling */
.container {
margin-top: 200px;
}
.control-buttons {
margin-top: 10px;
}
</style>
</head>
<body>
<h2>Video Control</h2>
<video id="videoPlayer" width="320" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div class="control-buttons">
25 | P a g e
<button onclick="playVideo()">Play Video</button>
<button onclick="pauseVideo()">Pause Video</button>
</div>
</div>
<script>
// Animation Variables
let box = document.getElementById("animatedBox");
let pos = 0;
let animation;
26 | P a g e
</body>
</html>
Output:
27 | P a g e
Practical 15
Program to illustrate the implementation of Slideshow, Banner in
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slideshow & Banner Example</title>
<style>
/* Slideshow container */
.slideshow-container {
max-width: 600px;
position: relative;
margin: auto;
overflow: hidden;
}
/* Slide images */
.slides {
display: none;
width: 100%;
}
/* Navigation buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.3s;
border-radius: 0 3px 3px 0;
user-select: none;
}
.dot {
28 | P a g e
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
cursor: pointer;
}
.active {
background-color: #717171;
}
</style>
</head>
<body>
<script>
let slideIndex = 1;
let slideInterval;
showSlide(slideIndex);
29 | P a g e
// Function to show the current slide
function showSlide(n) {
let slides = document.getElementsByClassName("slides");
let dots = document.getElementsByClassName("dot");
</body>
</html>
Output:
30 | P a g e
Practical 16
Program to develop a quiz application with multiple-choice
questions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<style>
/* Basic styling for the quiz */
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f2f5;
margin: 0;
}
.quiz-container {
max-width: 500px;
padding: 20px;
background: white;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.question {
font-size: 1.2em;
margin-bottom: 20px;
}
.options button {
display: block;
width: 100%;
padding: 10px;
margin: 8px 0;
font-size: 1em;
cursor: pointer;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
transition: background-color 0.3s ease;
}
.options button:hover {
background-color: #f0f0f0;
}
.score {
font-size: 1.2em;
color: #4CAF50;
margin-top: 20px;
}
</style>
31 | P a g e
</head>
<body>
<div class="quiz-container">
<h1>Quiz Application</h1>
<div id="quiz">
<p id="question" class="question"></p>
<div class="options">
<button onclick="checkAnswer(0)">Option 1</button>
<button onclick="checkAnswer(1)">Option 2</button>
<button onclick="checkAnswer(2)">Option 3</button>
<button onclick="checkAnswer(3)">Option 4</button>
</div>
</div>
<p id="score" class="score"></p>
</div>
<script>
// Quiz questions array
const quizQuestions = [
{
question: "What is the capital of France?",
options: ["Berlin", "Madrid", "Paris", "Rome"],
answer: 2
},
{
question: "Which planet is known as the Red Planet?",
options: ["Earth", "Jupiter", "Mars", "Venus"],
answer: 2
},
{
question: "Who wrote 'To Kill a Mockingbird'?",
options: ["Harper Lee", "Ernest Hemingway", "F. Scott Fitzgerald", "Mark Twain"],
answer: 0
},
{
question: "What is the smallest prime number?",
options: ["1", "2", "3", "0"],
answer: 1
},
];
let currentQuestionIndex = 0;
let score = 0;
// Load a question
function loadQuestion() {
const questionElement = document.getElementById("question");
const options = document.querySelectorAll(".options button");
questionElement.textContent = quizQuestions[currentQuestionIndex].question;
options.forEach((button, index) => {
button.textContent = quizQuestions[currentQuestionIndex].options[index];
});
}
32 | P a g e
// Check the user's answer
function checkAnswer(selectedOption) {
const correctAnswer = quizQuestions[currentQuestionIndex].answer;
currentQuestionIndex++;
</body>
</html>
Output:
33 | P a g e