0% found this document useful (0 votes)
31 views

JavascriptPracticalFileakash

Uploaded by

dk041202
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)
31 views

JavascriptPracticalFileakash

Uploaded by

dk041202
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/ 33

PRACTICAL FILE

SCRIPT CODING lab


Program: BTECH CSE Data Science and
Artificial Intelligence (IBM) 5th Semester
Course Code: CSE-506-22
Session: 2024-25

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

S. No List of Practicals Page No

1 Program to implement Hello using JavaScript 3


Program to implement various Operators using
2 4-6
JavaScript
Program to implement Conditional Operators using
3 7-8
JavaScript
Program to Implement If-Else Statement using
4 9
JavaScript
Program to illustrate the Loops (For, while, do-while)
5 10-11
in JavaScript
Program to illustrate the usage of Functions in
6 12-13
JavaScript
Program to illustrate the usage of Events in
7 14
JavaScript
Program to illustrate the usage of Cookies in
8 15-16
JavaScript
Program to illustrate the Page direction in JavaScript
9 17

10 Program to illustrate the Dialog Boxes in JavaScript 18-19


Program to Illustrate the Page Printing in JavaScript
11 20
Program to Implement Error Handling in JavaScript
12 21-22
Program to Implement form validation using
13 JavaScript to ensure input correctness (e.g., email 23-24
validation, password strength).
Program to illustrate the usage of Animation &
14 Multimedia in JavaScript 25-27

Program to illustrate the implementation of


15 Slideshow, Banner in JavaScript. 28-30

Program to develop a quiz application with multiple-


16 31-33
choice questions.

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&lt&lt1 </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&lt1</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&lt=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;

let isRaining = false;


let umbrellaReminder = (!isRaining) ? "Umbrella is not needed" : "Need an Umbrella";
document.getElementById("logicalNot").textContent = "Logical Not: " + umbrellaReminder;

// Ternary Operator in Function


function getGrade(score){
return (score >=90) ? 'A' : (score >= 80) ? 'B': (score >= 70) ? 'C' : 'F';
}

let score = 85;


let grade = getGrade(score);

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;

let resultElement = document.getElementById("result");

// check for positive, negative or zero


// if-else condition
if (number > 0) {
resultElement.innerHTML = "The number is positive";
} else if (number < 0) {
resultElement.innerHTML = "The number is negative";
} else{
resultElement.innerHTML = "The number is zero";
}
}
</script>
</body>
</html>

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>

<h1>JavaScript Functions with User Input</h1>

<!-- Input Fields for Area Calculation -->


<label for="length">Enter the length of the rectangle:</label>
<input type="number" id="length" required><br><br>

<label for="width">Enter the width of the rectangle:</label>


<input type="number" id="width" required><br><br>

<button onclick="calculateArea()">Calculate Area</button>


<p id="area"></p>

<!-- Input Field for Greeting Message -->


<label for="name">Enter your name:</label>
<input type="text" id="name" required><br><br>

<button onclick="displayGreeting()">Show Greeting</button>


<p id="greeting"></p>

<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.";
}
}

// Function to display a greeting message with user input


function displayGreeting() {
var name = document.getElementById("name").value;
if(name) {
document.getElementById("greeting").innerHTML = "Hello, " + name + "! Welcome to learning
JavaScript.";
} else {
document.getElementById("greeting").innerHTML = "Please enter your name.";
}
}
</script>

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");

// Define an event listener for the button's 'click' event


button.addEventListener("click", function() {
// Display an alert when the button is clicked
alert("Button was clicked!");
// Update the paragraph text
messageParagraph.textContent = "You clicked the button!";
});
</script>
</body>
</html>

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>

<h1>Cookie Example in JavaScript</h1>

<label for="cookieName">Cookie Name:</label>


<input type="text" id="cookieName" placeholder="Enter cookie name"><br><br>

<label for="cookieValue">Cookie Value:</label>


<input type="text" id="cookieValue" placeholder="Enter cookie value"><br><br>

<button onclick="setCookie()">Set Cookie</button>


<button onclick="getCookie()">Get Cookie</button>
<button onclick="deleteCookie()">Delete Cookie</button>

<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!`;
}

// Function to get a cookie


function getCookie() {
const name = document.getElementById("cookieName").value + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(';');
let foundCookie = "Cookie not found!";
cookieArray.forEach(cookie => {
cookie = cookie.trim();
if (cookie.indexOf(name) == 0) {
foundCookie = "Cookie Value: " + cookie.substring(name.length, cookie.length);
}
});
document.getElementById("output").textContent = foundCookie;
}

// Function to delete a cookie

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>

<h1>Page Redirection in JavaScript</h1>

<button onclick=”redirectToPage()”>Go to Google</button>


<button onclick=”goBack()”>Go Back</button>

<script>
// Function to redirect to a specific page
function redirectToPage() {
window.location.href = “https://www.google.com”; // Redirects to Google
}

// Function to go back to the previous page


function goBack() {
window.history.back(); // Goes back to the previous page in history
}
</script>

</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>

<h1>Dialog Boxes in JavaScript</h1>

<button onclick="showAlert()">Show Alert</button>


<button onclick="showPrompt()">Show Prompt</button>
<button onclick="showConfirm()">Show Confirm</button>

<p id="output"></p>

<script>
// Function to display an alert dialog
function showAlert() {
alert("This is an alert box!");
}

// Function to display a prompt dialog


function showPrompt() {
const name = prompt("Please enter your name:", "Guest");
if (name != null) {
document.getElementById("output").textContent = "Hello, " + name + "!";
} else {
document.getElementById("output").textContent = "No name entered.";
}
}

// Function to display a confirm dialog


function showConfirm() {
const result = confirm("Do you want to continue?");
if (result) {
document.getElementById("output").textContent = "You chose to continue.";
} else {
document.getElementById("output").textContent = "You canceled the action.";
}
}
</script>

</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>

<h1>Page Printing in JavaScript</h1>


<p>This is an example of how to print a web page using JavaScript.</p>

<button onclick=”printPage()”>Print This Page</button>

<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>

<h1>Error Handling in JavaScript</h1>

<label for="numberInput">Enter a number:</label>


<input type="text" id="numberInput" placeholder="Enter a number">
<button onclick="processInput()">Submit</button>

<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";

const number = Number(input);


if (number < 0) throw "Please enter a positive number";

output.textContent = "You entered a valid number: " + number;


} catch (error) {
output.textContent = "Error: " + error;
} finally {
document.getElementById("numberInput").value = ""; // Clear input field
}
}
</script>

</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");
}

return isValid; // Prevents form submission if there are errors


}
</script>
</body>
</html>

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>

<h1>Animation & Multimedia in JavaScript</h1>

<!-- Animated Box -->


<div id="animatedBox"></div>
<button onclick="startAnimation()">Start Animation</button>
<button onclick="stopAnimation()">Stop Animation</button>

<!-- Multimedia Section -->


<div class="container">
<h2>Audio Control</h2>
<audio id="audioPlayer" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-
1.mp3"></audio>
<div class="control-buttons">
<button onclick="playAudio()">Play Audio</button>
<button onclick="pauseAudio()">Pause Audio</button>
</div>

<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;

// Function to start the animation


function startAnimation() {
clearInterval(animation); // Clear previous intervals if any
animation = setInterval(moveBox, 10); // Move box every 10ms
}

// Function to stop the animation


function stopAnimation() {
clearInterval(animation); // Stop the interval
}

// Function to move the box


function moveBox() {
if (pos >= window.innerWidth - 50) {
pos = 0; // Reset position if it reaches end of screen
} else {
pos++; // Increment position
box.style.left = pos + 'px'; // Move box horizontally
}
}

// Multimedia control functions


const audioPlayer = document.getElementById("audioPlayer");
const videoPlayer = document.getElementById("videoPlayer");

// Function to play audio


function playAudio() {
audioPlayer.play();
}

// Function to pause audio


function pauseAudio() {
audioPlayer.pause();
}

// Function to play video


function playVideo() {
videoPlayer.play();
}

// Function to pause video


function pauseVideo() {
videoPlayer.pause();
}
</script>

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;
}

/* Position the "next button" to the right */


.next {
right: 0;
border-radius: 3px 0 0 3px;
}

/* Active dot indicator */


.dot-container {
text-align: center;
margin-top: 10px;
}

.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>

<h1>JavaScript Slideshow/Banner Example</h1>

<!-- Slideshow container -->


<div class="slideshow-container">
<!-- Slides -->
<img class="slides" src="https://via.placeholder.com/600x400?text=Slide+1" alt="Slide 1">
<img class="slides" src="https://via.placeholder.com/600x400?text=Slide+2" alt="Slide 2">
<img class="slides" src="https://via.placeholder.com/600x400?text=Slide+3" alt="Slide 3">

<!-- Navigation buttons -->


<a class="prev" onclick="changeSlide(-1)">&#10094;</a>
<a class="next" onclick="changeSlide(1)">&#10095;</a>
</div>

<!-- Dot indicators -->


<div class="dot-container">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>

<script>
let slideIndex = 1;
let slideInterval;
showSlide(slideIndex);

// Function to change slides


function changeSlide(n) {
clearInterval(slideInterval); // Stop auto transition on manual click
showSlide(slideIndex += n);
autoSlide(); // Restart auto transition
}

// Function to set current slide


function currentSlide(n) {
clearInterval(slideInterval); // Stop auto transition on manual click
showSlide(slideIndex = n);
autoSlide(); // Restart auto transition
}

29 | P a g e
// Function to show the current slide
function showSlide(n) {
let slides = document.getElementsByClassName("slides");
let dots = document.getElementsByClassName("dot");

if (n > slides.length) { slideIndex = 1; }


if (n < 1) { slideIndex = slides.length; }

// Hide all slides


for (let slide of slides) {
slide.style.display = "none";
}

// Remove active status from all dots


for (let dot of dots) {
dot.className = dot.className.replace(" active", "");
}

// Show the current slide and set the active dot


slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}

// Function to start automatic slide transition


function autoSlide() {
slideInterval = setInterval(() => {
showSlide(++slideIndex);
}, 3000); // Change slide every 3 seconds
}

// Start automatic slideshow


autoSlide();
</script>

</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;

if (selectedOption === correctAnswer) {


score++;
}

currentQuestionIndex++;

if (currentQuestionIndex < quizQuestions.length) {


loadQuestion();
} else {
showScore();
}
}

// Display the final score


function showScore() {
document.getElementById("quiz").style.display = "none";
document.getElementById("score").textContent = `Your score: ${score} out of ${quizQuestions.length}`;
}

// Load the first question when the page loads


loadQuestion();
</script>

</body>
</html>

Output:

33 | P a g e

You might also like