0% found this document useful (0 votes)
11 views34 pages

JavaScript SLA

JavaScript_SLA (self learning assignment)

Uploaded by

samrudhiambekar4
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)
11 views34 pages

JavaScript SLA

JavaScript_SLA (self learning assignment)

Uploaded by

samrudhiambekar4
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

Self-Learning Assignment (SLA)

Subject: JavaScript Subject Code: 7T203

Unit 1
Question 1:

Write a short note on key features of JavaScript and explain its importance in web
development.

Ans:-

JavaScript is a lightweight, interpreted scripting language used to make web pages


interactive and dynamic. It runs directly in the browser and allows developers to control
the behavior of web pages.

Key Features:

1. Lightweight & Interpreted: Runs line by line in browsers without compilation.


2. Dynamic Typing: No need to declare variable types.
3. Object-Based: Supports objects and prototypes for code reusability.
4. Event-Driven: Responds to user actions like clicks or keystrokes.
5. Asynchronous: Handles background tasks using callbacks, promises, or
async/await.
6. DOM Manipulation: Can modify HTML and CSS dynamically.
7. Cross-Platform: Works on all browsers and operating systems.

Importance in Web Development:

 Adds interactivity to web pages (forms, menus, animations).


 Enables client-side validation, reducing server load.
 Supports dynamic updates using AJAX without reloading pages.
 Forms the base for modern frameworks like React, Angular, and Vue.
 Works both on front-end and back-end (with [Link]).

Example:
<button onclick="alert('Hello, JavaScript!')">Click Me</button>
Question 2:

Develop a JavaScript program using if-else and switch statements to evaluate a


student’s grade based on marks.

Ans:-

Theory:

Use conditional statements to map numeric marks to letter grades. if-else is good for ranges;
switch can be used by mapping grade categories or using [Link] on percentage range.

JavaScript Code:

// Using if-else

function gradeIfElse(marks) {

if (marks >= 90 && marks <= 100)

return "Grade A";

else if (marks >= 80)

return "Grade B";

else if (marks >= 70)

return "Grade C";

else if (marks >= 60)

return "Grade D";

else

return "Grade F";

// Using switch

function gradeSwitch(marks) {

let tens = [Link](marks / 10);

switch (tens) {

case 10:

case 9: return "Grade A";

case 8: return "Grade B";


case 7: return "Grade C";

case 6: return "Grade D";

default: return "Grade F";

Question 3:

Create an example that demonstrates different looping structures (for, while, do-while)
to print even numbers up to 50.

Ans:-

Theory:

Loops are used to repeat actions. for is compact for known iterations, while checks
condition before iteration, do-while checks after first iteration.

Example & Explanation:

Print even numbers from 2 to 50 using three loop types.

JavaScript Code:

<!DOCTYPE html>

<html>

<head>

<title>Looping Structures in JavaScript</title>

<meta charset="UTF-8">

</head>

<body>

<h2>Printing Even Numbers up to 50 using Different Loops</h2>

<pre id="output"></pre>

<script>

let result = "";


// --- Using for loop ---

result += "Even numbers using for loop:\n";

for (let i = 2; i <= 50; i += 2) {

result += i + " ";

result += "\n\n";

// --- Using while loop ---

result += "Even numbers using while loop:\n";

let j = 2;

while (j <= 50) {

result += j + " ";

j += 2;

result += "\n\n";

// --- Using do-while loop ---

result += "Even numbers using do-while loop:\n";

let k = 2;

do {

result += k + " ";

k += 2;

} while (k <= 50);

// Display output in the web page

[Link]("output").textContent = result;

</script>

</body>

</html>
Output

Unit 2
Question 1:

Write a JavaScript code to add, sort, and display array elements using push() and sort()
methods.

Ans:-

Theory:

Arrays store ordered lists. push() adds elements to end. sort() orders elements; for
numbers provide compare function because default sorts lexicographically.

Example & Explanation:

Add numbers to an array, then sort ascending and display.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Array Add, Sort, and Display</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 30px;

h2 {
color: #2c3e50;

pre {

background-color: #f4f4f4;

padding: 10px;

border: 1px solid #ccc;

</style>

</head>

<body>

<h2>JavaScript Array: Add, Sort, and Display</h2>

<p><strong>Open your browser console</strong> (Right-click →


Inspect → Console) to see the output.</p>

<script>

// Initialize an empty array

let numbers = [];

// Add elements using push()

[Link](42);

[Link](17);

[Link](8);

[Link](99);

[Link](23);

[Link]("Array before sorting:");

[Link](numbers);

// Sort the array in ascending order

[Link](function(a, b) {

return a - b;

});
[Link]("Array after sorting:");

[Link](numbers);

</script>

</body>

</html>

Output

Question 2:

Create a function with parameters and return value that calculates the area of a
rectangle.

Ans:-

Theory:

Functions encapsulate code. Parameters accept inputs; return returns value. Area = length *
breadth.

Example & Explanation:

Function area(l,b) returns l*b.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Rectangle Area Calculator</title>


<style>

body {

font-family: Arial, sans-serif;

margin: 30px;

input {

margin: 5px 0;

</style>

</head>

<body>

<h2>Calculate Area of a Rectangle</h2>

<label for="length">Length:</label><br>

<input type="number" id="length"><br>

<label for="width">Width:</label><br>

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

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

<p id="result"></p>

<script>

// Function to calculate rectangle area

function calculateRectangleArea(length, width) {

return length * width;

// Function to get input values and show result

function showArea() {

let length =
parseFloat([Link]('length').value);

let width =
parseFloat([Link]('width').value);
if (isNaN(length) || isNaN(width)) {

[Link]('result').innerText = "Please
enter valid numbers.";

return;

let area = calculateRectangleArea(length, width);

[Link]('result').innerText = "Area of
rectangle: " + area;

</script>

</body>

</html>

Output

Question 3:

Write a script that accepts a string and performs string operations: find its length,
convert to uppercase, and extract a substring.

Ans:-

Theory:

String methods: .length, .toUpperCase(), .substring(start,end) or .slice().

Example & Explanation:

Given 'Hello JavaScript' find length, uppercase, substring from 6 to 16.

JavaScript Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>String Operations</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 30px;

input {

width: 300px;

padding: 5px;

margin-bottom: 10px;

</style>

</head>

<body>

<h2>String Operations</h2>

<label for="inputString">Enter a string:</label><br>

<input type="text" id="inputString" placeholder="Type


something..."><br>

<button onclick="performStringOperations()">Run Operations</button>

<h3>Results:</h3>

<p><strong>Length:</strong> <span id="length"></span></p>

<p><strong>Uppercase:</strong> <span id="uppercase"></span></p>

<p><strong>Substring (0–5):</strong> <span


id="substring"></span></p>

<script>
function performStringOperations() {

let str = [Link]('inputString').value;

// Perform operations

let length = [Link];

let upper = [Link]();

let substring = [Link](0, 5);

// Display results

[Link]('length').innerText = length;

[Link]('uppercase').innerText = upper;

[Link]('substring').innerText = substring;

</script>

</body>

</html>

Output

Unit 3
Question 1:

Design an HTML form with text boxes, radio buttons, and checkboxes, and write
JavaScript to validate the input fields.

Ans:-

Theory:
Form validation ensures required fields are filled and values are valid. Use HTML attributes
and JS for custom checks. Prevent form submission when invalid.

Example & Explanation:

HTML form with name, gender (radio), interests (checkboxes), and email. JS checks
required fields and valid email pattern.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Form with Validation</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 30px;

.error {

color: red;

label {

display: block;

margin-top: 10px;

</style>

</head>

<body>

<h2>User Information Form</h2>

<form id="userForm" onsubmit="return validateForm()">

<!-- Name Text Box -->


<label for="name">Name:</label>

<input type="text" id="name" name="name">

<!-- Email Text Box -->

<label for="email">Email:</label>

<input type="text" id="email" name="email">

<!-- Radio Buttons -->

<label>Gender:</label>

<input type="radio" name="gender" value="Male" id="male">


<label for="male">Male</label>

<input type="radio" name="gender" value="Female" id="female">


<label for="female">Female</label>

<!-- Checkboxes -->

<label>Interests:</label>

<input type="checkbox" name="interests" value="Music"


id="music"> <label for="music">Music</label>

<input type="checkbox" name="interests" value="Sports"


id="sports"> <label for="sports">Sports</label>

<input type="checkbox" name="interests" value="Reading"


id="reading"> <label for="reading">Reading</label>

<br><br>

<button type="submit">Submit</button>

<p class="error" id="errorMsg"></p>

</form>

<script>

function validateForm() {

let name = [Link]("name").[Link]();

let email = [Link]("email").[Link]();

let gender =
[Link]('input[name="gender"]:checked');
let interests =
[Link]('input[name="interests"]:checked');

let errorMsg = [Link]("errorMsg");

// Clear previous error message

[Link] = "";

// Validate name

if (name === "") {

[Link] = "Please enter your name.";

return false;

// Validate email

if (email === "") {

[Link] = "Please enter your email.";

return false;

} else if (!validateEmail(email)) {

[Link] = "Please enter a valid email


address.";

return false;

// Validate gender

if (!gender) {

[Link] = "Please select your gender.";

return false;

// Validate interests

if ([Link] === 0) {

[Link] = "Please select at least one


interest.";

return false;
}

alert("Form submitted successfully!");

return true; // Allow form submission

// Basic email pattern validation

function validateEmail(email) {

let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

return [Link](email);

</script>

</body>

</html>

Output

Question 2:

Write a JavaScript program to enable/disable form elements based on user selections


(for example, disabling submit until all required fields are filled).

Theory:

Use event listeners to track inputs and enable/disable elements. This improves UX by
preventing invalid submits.

Example & Explanation:

Disable submit until name and email are filled and a checkbox 'agree' is checked.
JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Enable/Disable Submit</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 50px;

input, select, button {

display: block;

margin: 15px 0;

padding: 10px;

width: 300px;

button:disabled {

background-color: #ccc;

cursor: not-allowed;

</style>

</head>

<body>

<h2>Form Validation Example</h2>

<form id="myForm">

<input type="text" id="name" placeholder="Enter your name"


required>
<input type="email" id="email" placeholder="Enter your email"
required>

<select id="country" required>

<option value="">Select a country</option>

<option value="us">United States</option>

<option value="uk">United Kingdom</option>

<option value="ca">Canada</option>

</select>

<button type="submit" id="submitBtn" disabled>Submit</button>

</form>

<script>

const form = [Link]('myForm');

const nameField = [Link]('name');

const emailField = [Link]('email');

const countryField = [Link]('country');

const submitBtn = [Link]('submitBtn');

function validateForm() {

const nameFilled = [Link]() !== '';

const emailFilled = [Link]() !== '';

const countrySelected = [Link] !== '';

// Enable the button only if all fields are filled

[Link] = !(nameFilled && emailFilled &&


countrySelected);

// Attach event listeners

[Link]('input', validateForm);

[Link]('input', validateForm);

[Link]('change', validateForm);
// Optional: Prevent actual submission to demonstrate functionality

[Link]('submit', function (e) {

[Link]();

alert('Form submitted successfully!');

});

</script>

</body>

</html>

Output

Question 3:

Develop a web page that uses event handling to change the color of a text box when the
mouse moves over it and reverts when the mouse moves out.

Theory:

Use mouseover and mouseout (or mouseenter/mouseleave) events to change style


properties dynamically..

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<title>Mouse Event Color Change</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 50px;

background-color: #f4f4f4;

#textbox {

width: 300px;

height: 100px;

font-size: 18px;

padding: 10px;

border: 2px solid #ccc;

transition: background-color 0.3s ease;

</style>

</head>

<body>

<h2>Hover Over the Text Box</h2>

<textarea id="textbox" placeholder="Hover over me..."></textarea>

<script>

const textbox = [Link]('textbox');

// Mouse enters the textarea

[Link]('mouseover', function () {

[Link] = '#d1ecf1'; // light blue

});

// Mouse leaves the textarea


[Link]('mouseout', function () {

[Link] = ''; // revert to default

});

</script>

</body>

</html>

Output

Unit 4
Question 1:

Write JavaScript code to create, read, and delete cookies with a specific expiration time.

Ans:-

Theory:

Cookies store small pieces of data. [Link] can set cookies with 'name=value;
expires=DATE; path=/' etc. To delete, set expiration to past date.

Example & Explanation:

Functions setCookie, getCookie, deleteCookie.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<title>Cookie Manager Demo</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 40px;

input, button {

padding: 10px;

margin: 8px 0;

width: 300px;

#output {

margin-top: 20px;

padding: 10px;

background-color: #f1f1f1;

width: 320px;

button {

cursor: pointer;

</style>

</head>

<body>

<h2>JavaScript Cookie Manager</h2>


<label>

Cookie Name:<br>

<input type="text" id="cookieName" placeholder="e.g., user">

</label><br>

<label>

Cookie Value:<br>

<input type="text" id="cookieValue" placeholder="e.g., Alice">

</label><br>

<label>

Expiration (minutes):<br>

<input type="number" id="cookieExpire" placeholder="e.g., 10">

</label><br>

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

<button onclick="getCookieHandler()">Read Cookie</button>

<button onclick="deleteCookieHandler()">Delete Cookie</button>

<div id="output"></div>

<script>

// Set cookie with expiration in minutes

function setCookie(name, value, minutesToExpire) {

const expires = new Date([Link]() + minutesToExpire * 60 *


1000).toUTCString();
[Link] =
`${encodeURIComponent(name)}=${encodeURIComponent(value)};
expires=${expires}; path=/`;

// Get cookie by name

function getCookie(name) {

const decodedCookies =
decodeURIComponent([Link]).split(';');

const cookieName = name + "=";

for (let cookie of decodedCookies) {

cookie = [Link]();

if ([Link](cookieName) === 0) {

return [Link]([Link]);

return null;

// Delete cookie by setting its expiration to the past

function deleteCookie(name) {

[Link] = `${encodeURIComponent(name)}=; expires=Thu, 01


Jan 1970 [Link] UTC; path=/`;

// Handlers

function setCookieHandler() {

const name = [Link]('cookieName').[Link]();

const value =
[Link]('cookieValue').[Link]();
const minutes =
parseInt([Link]('cookieExpire').value, 10);

if (name && value && !isNaN(minutes)) {

setCookie(name, value, minutes);

displayOutput(`Cookie '${name}' set for ${minutes} minutes.`);

} else {

displayOutput("Please fill in all fields correctly.");

function getCookieHandler() {

const name = [Link]('cookieName').[Link]();

if (name) {

const value = getCookie(name);

if (value !== null) {

displayOutput(`Cookie value for '${name}': ${value}`);

} else {

displayOutput(`Cookie '${name}' not found.`);

} else {

displayOutput("Please enter a cookie name to read.");

function deleteCookieHandler() {

const name = [Link]('cookieName').[Link]();

if (name) {

deleteCookie(name);
displayOutput(`Cookie '${name}' deleted.`);

} else {

displayOutput("Please enter a cookie name to delete.");

function displayOutput(message) {

[Link]('output').textContent = message;

</script>

</body>

</html>

Output

Question 3:

Develop a script to open a new browser window, write content into it, and then close it
using JavaScript functions.

Ans:-

Theory:

Use RegExp to test email pattern. A simple, practical regex is:


/^[^\s@]+@[^\s@]+\.[^\s@]+$/. For stricter validation, more complex expressions exist.

Example & Explanation:

Validate an email input and show message.


JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Open and Close Window</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 50px;

text-align: center;

button {

padding: 10px 20px;

font-size: 16px;

</style>

</head>

<body>

<h2>Open and Close a New Window with JavaScript</h2>

<button onclick="openWriteCloseWindow()">Open Window</button>

<script>

function openWriteCloseWindow() {

// Open a new window (width: 400px, height: 300px)

const newWin = [Link]("", "NewWindow",


"width=400,height=300");

// Check if popup was blocked

if (!newWin) {

alert("Popup was blocked. Please allow popups for this site.");


return;

// Write content into the new window

[Link](`

<!DOCTYPE html>

<html>

<head>

<title>Popup Content</title>

<style>

body {

font-family: Arial, sans-serif;

background-color: #f9f9f9;

text-align: center;

padding-top: 40px;

</style>

</head>

<body>

<h2>This is a new window</h2>

<p>It will close automatically in 5 seconds.</p>

</body>

</html>

`);

// Close the document so styles apply

[Link]();

// Close the new window after 5 seconds

setTimeout(() => {

[Link]();
}, 5000);

</script>

</body>

</html>

Output

Unit 5
Question 1:

Create a web page that demonstrates image rollover effects (changing an image when
the mouse pointer moves over it).

Ans:-

Theory:

Image rollover swaps image src on mouseover/mouseout for hover effects. Useful for
buttons and navigation.

Example & Explanation:

Two images: img1 and img2, swap on hover.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Image Rollover Demo</title>


<style>

body {

text-align: center;

padding-top: 50px;

font-family: Arial, sans-serif;

img {

width: 300px;

height: auto;

cursor: pointer;

transition: 0.3s;

</style>

</head>

<body>

<h2>Hover Over the Image</h2>

<img

id="rolloverImage"

src="[Link]

alt="Rollover Image"

onmouseover="changeImage()"

onmouseout="restoreImage()"

>

<script>

function changeImage() {

[Link]("rolloverImage").src =

"[Link]

}
function restoreImage() {

[Link]("rolloverImage").src =

"[Link]

</script>

</body>

</html>

Output

Question 2:

Develop a simple JavaScript image slideshow that automatically changes images every
few seconds.

Ans:-

Theory:

Use setInterval to change image index and update src. Can include previous/next controls
and pause on hover.

Example & Explanation:

A basic slideshow with array of image URLs and auto-change every 3 seconds.

JavaScript Code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Auto Image Slideshow</title>

<style>
body {

text-align: center;

font-family: Arial, sans-serif;

background-color: #f4f4f4;

padding-top: 50px;

img {

width: 500px;

height: auto;

border: 4px solid #ccc;

box-shadow: 0 0 10px rgba(0,0,0,0.2);

transition: opacity 0.5s ease-in-out;

</style>

</head>

<body>

<h2>JavaScript Image Slideshow</h2>

<img id="slideshow"
src="[Link] alt="Slideshow
Image">

<script>

const images = [

"[Link]

"[Link]

"[Link]

"[Link]

];

let currentIndex = 0;
const slideshow = [Link]("slideshow");

function changeImage() {

currentIndex = (currentIndex + 1) % [Link];

[Link] = images[currentIndex];

// Change image every 3 seconds (3000ms)

setInterval(changeImage, 3000);

</script>

</body>

</html>

Output

Question 3:

Write a JavaScript program to disable right-click and display a custom alert message
like 'Right-click is disabled for security.'

Ans:-

Theory:

Capture contextmenu event on document and prevent default to disable right-click menu.
Show custom message using alert or custom modal.

Example & Explanation:

Disable context menu and show alert.

JavaScript Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Disable Right-Click</title>

<style>

body {

font-family: Arial, sans-serif;

text-align: center;

padding-top: 100px;

</style>

</head>

<body>

<h2>Right-Click Disabled Demo</h2>

<p>Try right-clicking anywhere on this page.</p>

<script>

// Disable right-click

[Link]('contextmenu', function (e) {

[Link](); // Prevent default right-click menu

alert('Right-click is disabled for security.');

});

</script>

</body>

</html>

Output

You might also like