0% found this document useful (0 votes)
3 views21 pages

JS(Casestudy)

The document provides a series of JavaScript programs for web pages that interact with users, including greeting users by name, checking if a number is positive or negative, and managing tasks. It explains the use of the prompt() function for user input, the structure of HTML documents, and how to manipulate the DOM to create interactive web applications. Additionally, it discusses the limitations of prompt() and the importance of using HTML forms for complex user interactions.

Uploaded by

karthi keyini121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

JS(Casestudy)

The document provides a series of JavaScript programs for web pages that interact with users, including greeting users by name, checking if a number is positive or negative, and managing tasks. It explains the use of the prompt() function for user input, the structure of HTML documents, and how to manipulate the DOM to create interactive web applications. Additionally, it discusses the limitations of prompt() and the importance of using HTML forms for complex user interactions.

Uploaded by

karthi keyini121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CASE-STUDY-1

1. You are creating a web page that greets the user by name. Write a JavaScript program
that asks the user for their name using a prompt () dialog and then displays a greeting
message like “Hello, [name]!” on the web page. Also, explain how prompt () works
and why it is useful for getting user input in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Greeting Page</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
margin: 0;
}
h1 {
color: #333;
}
</style>
</head>
<body>

<h1 id="greeting"></h1>

<script>
// Ask the user for their name
const name = prompt("What is your name?");

// Display the greeting message


if (name) {
document.getElementById('greeting').innerText = `Hello, ${name}!`;
} else {
document.getElementById('greeting').innerText = "Hello, Stranger!";
}
</script>

</body>
</html>

Explanation

1. <!DOCTYPE html>

 This is the document type declaration.


 It tells the browser that this is an HTML5 document, so it will be rendered according
to HTML5 standards.

2. <html lang="en">

 This is the root element of the HTML document.


 The lang="en" attribute specifies that the language of the document is English.

3. <head>

 The <head> section contains metadata and settings for the document that are not
displayed on the webpage.

4. <meta charset="UTF-8" />

 Sets the character encoding to UTF-8, which supports most characters and symbols
(including special characters like emojis).
 Ensures that text and symbols are displayed correctly.

5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 This makes the webpage responsive to different screen sizes:


o width=device-width → Sets the width to match the device's screen width.
o initial-scale=1.0 → Sets the initial zoom level to 100%.

6. <title>Greeting Page</title>
 Sets the title of the webpage (shown on the browser tab).

7. <style> (CSS Section)

This section defines the styling of the webpage using CSS.

8. body { ... }

 font-family: Arial, sans-serif; → Sets the font to Arial (or a sans-serif font if
Arial is unavailable).
 display: flex; → Uses Flexbox to align content.
 justify-content: center; → Centers the content horizontally.
 align-items: center; → Centers the content vertically.
 height: 100vh; → Sets the height to 100% of the viewport height.
 background-color: #f4f4f9; → Sets the background color to light gray.
 margin: 0; → Removes any default margin from the body.

9. h1 { ... }

 color: #333; → Sets the text color of the <h1> element to dark gray.

10. <body>

 Contains the content of the webpage.

11. <h1 id="greeting"></h1>

 A heading element (h1) with an ID of greeting is defined to display the greeting


message.
 The id allows JavaScript to access and modify it.

12. <script> (JavaScript Section)

This section contains the JavaScript code that makes the webpage interactive.

13. const name = prompt("What is your name?");

 prompt() → Opens a dialog box asking the user to input their name.
 The user's input is stored in the name variable.
 If the user presses "Cancel," name will be null.

14. if (name) { ... } else { ... }

 Condition Check:
o If name is truthy (not empty or null), it will display a personalized message.
o If name is falsy (empty or null), it will display a default greeting.

15. document.getElementById('greeting').innerText = ...

 document.getElementById('greeting') → Selects the <h1> element with the


id="greeting".
 innerText → Sets the content of the <h1> element:
o If user enters "Alex" → Displays "Hello, Alex!"
o If user cancels or leaves it blank → Displays "Hello, Stranger!"

16. </body>

 Ends the body section.

17. </html>

 Closes the HTML document.

✅ How It Works:

1. When the page loads, a prompt() box asks for the user’s name.
2. The input is stored in the name variable.
3. The if...else statement determines the greeting message.
4. The message is displayed inside the <h1> element using innerText.
Output:

Output of the Code:

1. When the page loads:


A prompt box appears asking:
➡️"What is your name?"

➡️Scenario 1:

✅ User enters a name (e.g., "Alex")

 Output on the webpage:


👉 Hello, Alex!

➡️Scenario 2:

✅ User clicks "Cancel" or leaves the input empty

 Output on the webpage:


👉 Hello, Stranger!

prompt() in JavaScript

The prompt() function is a built-in JavaScript method that allows you to display a dialog
box asking the user for input. It temporarily pauses code execution until the user responds by
either entering text or canceling the dialog.

📌 Syntax:
let input = prompt(message, default);
Parameter Description
message (Optional) A string that is displayed as the message in the dialog box.
default
(Optional) A default value that appears in the input field. If omitted, the input
field is empty.
Return
Returns the user input as a string, or null if the user clicks Cancel.
Value

🛠️How prompt() Works:


1. A dialog box appears with:
o A text message (provided by message).
o An input field where the user can type.
o Two buttons: OK and Cancel.
2. ✅ If the user clicks OK:
o The text entered in the input field is returned as a string.
o Example: prompt("Enter your name:") → User types "Alex" → Returns
"Alex"
3. ❌ If the user clicks Cancel or closes the dialog:
o null is returned.
o Example: prompt("Enter your name:") → User clicks Cancel → Returns
null

🧠 Example 1 – Basic Example:


let name = prompt("What is your name?");
console.log("Hello, " + name + "!");

✅ If user enters "John" → Output: "Hello, John!"


❌ If user clicks Cancel → Output: "Hello, null!"

🧠 Example 2 – Using a Default Value:


let age = prompt("Enter your age:", "18");
console.log("You are " + age + " years old.");

 If user types 25 → Output: "You are 25 years old."


 If user clicks OK without typing → Output: "You are 18 years old."
 If user clicks Cancel → Output: "You are null years old."

💡 Why prompt() is Useful:

✅ Quick and Simple:

 prompt() is easy to implement — no need to create input fields in HTML manually.

✅ Ideal for Small Input Needs:

 Good for simple user input like names, ages, or quick confirmations.

✅ Blocks Execution Until Input is Received:

 Code execution is paused until the user responds, which ensures that the input is
processed before the next step.
🚫 Limitations of prompt()

❌ Limited Customization: The appearance of the prompt box is controlled by the browser
and can't be styled using CSS.
❌ Synchronous Blocking: Code execution stops until the user responds, which can be
inconvenient for larger applications.
❌ Not Ideal for Complex Forms: For more complex user input, using HTML forms and
input elements with event listeners is better.

✅ When to Use prompt()

 ✅ Simple user interactions


 ✅ Quick debugging/testing
 ✅ Capturing small pieces of information (like names or numbers)
 ✅ Prototyping and quick demos

🚀 Summary:

 prompt() is useful for collecting simple user input.


 It’s quick to implement but limited in customization and flexibility.
 For more advanced forms and user interactions, HTML <input> fields and event
handling are preferred.

2. Write a JavaScript program that gets a number from the user using prompt (), checks
whether the number is positive, negative, or zero using if or if-else statements, and
displays the result using alert() or document.write(). Also, explain the purpose and
usage of if and if-else statements in JavaScript.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Number Checker</title>

</head>

<body>
<script>

// Get a number from the user

let num = prompt("Enter a number:");

// Convert the input to a number type

num = Number(num);

// Check if the input is a valid number

if (isNaN(num)) {

alert("Please enter a valid number.");

} else {

// Check if the number is positive, negative, or zero

if (num > 0) {

alert(`${num} is a positive number.`);

} else if (num < 0) {

alert(`${num} is a negative number.`);

} else {

alert(`The number is zero.`);

</script>

</body>

</html>
3. You are creating a task management web page where users can add tasks without
reloading the page. The page contains an empty <ul> with the ID "taskList". Write a
JavaScript program that gets user input from a text box, creates a new <li> element
with that input, and appends it to the task list. Also, explain how the Document Object
Model (DOM) represents an HTML page as a tree of nodes and how the document
object is used to access and modify elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Task Manager</title>

<style>

body {

font-family: Arial, sans-serif;

background-color: #f4f4f9;

margin: 20px;

h1 {

color: #333;

#taskInput {

padding: 8px;

width: 250px;

border: 1px solid #ccc;

border-radius: 4px;
margin-right: 5px;

#addTaskBtn, #stopBtn {

padding: 8px 12px;

background-color: #28a745;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

margin-left: 5px;

#addTaskBtn:hover {

background-color: #218838;

#stopBtn {

background-color: #dc3545;

#stopBtn:hover {

background-color: #c82333;

ul {

list-style-type: none;

padding: 0;

li {
padding: 8px;

background-color: #e9ecef;

margin-top: 5px;

border-radius: 4px;

</style>

</head>

<body>

<h1>Task Manager</h1>

<!-- Task Input and Buttons -->

<input type="text" id="taskInput" placeholder="Enter a task..." />

<button id="addTaskBtn">Add Task</button>

<button id="stopBtn">Stop Program</button>

<!-- Task List -->

<ul id="taskList"></ul>

<script>

// Get references to the input box, buttons, and task list

const taskInput = document.getElementById('taskInput');

const addTaskBtn = document.getElementById('addTaskBtn');

const stopBtn = document.getElementById('stopBtn');

const taskList = document.getElementById('taskList');


// Function to add a task

function addTask() {

// Get the value from the input box

const task = taskInput.value.trim();

// Only add the task if it's not empty

if (task !== '') {

// Create a new <li> element

const listItem = document.createElement('li');

listItem.innerText = task;

// Append the new task to the task list

taskList.appendChild(listItem);

// Clear the input box after adding the task

taskInput.value = '';

} else {

alert("Please enter a valid task.");

// Add a click event to the "Add Task" button

addTaskBtn.addEventListener('click', addTask);
// Allow pressing "Enter" key to add a task

taskInput.addEventListener('keypress', (event) => {

if (event.key === 'Enter') {

addTask();

});

// Function to stop the program

function stopProgram() {

// Disable the input box and the "Add Task" button

taskInput.disabled = true;

addTaskBtn.disabled = true;

stopBtn.disabled = true;

// Show an alert

alert("Program stopped!");

// Add click event to the "Stop" button

stopBtn.addEventListener('click', stopProgram);

</script>

</body>

</html>

Explanation
🏗️HTML Explanation

HTML (Hypertext Markup Language) defines the structure of the web page.

1. <!DOCTYPE html>

 Declares the document as an HTML5 document.


 Ensures the browser interprets the HTML in standards mode.

2. <html lang="en">

 The <html> element is the root of the HTML document.


 lang="en" specifies that the document is in English.

3. <head> Section

Contains metadata and links to styles/scripts.

✅ <meta charset="UTF-8" />

 Sets the character encoding to UTF-8 (supports special characters like ä, é, etc.).

✅ <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 Makes the page responsive for different screen sizes (especially mobile).
 width=device-width → Sets the width to the device’s screen size.
 initial-scale=1.0 → Sets the zoom level to 1.

✅ <title>Task Manager</title>

 Sets the page title shown in the browser tab.

4. <style> Section

Defines CSS to style the page.

✅ body Styling

body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 20px;
}
 font-family: Arial, sans-serif; → Sets font style.
 background-color: #f4f4f9; → Light gray background.
 margin: 20px; → Adds space around the page content.

✅ h1 Styling

h1 {
color: #333;
}

 color: #333; → Dark gray text color for the heading.

✅ #taskInput Styling

#taskInput {
padding: 8px;
width: 250px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 5px;
}

 padding: 8px; → Adds space inside the input box.


 width: 250px; → Sets width.
 border: 1px solid #ccc; → Adds a light gray border.
 border-radius: 4px; → Rounds the corners.
 margin-right: 5px; → Adds space between input and button.

✅ #addTaskBtn Styling

#addTaskBtn {
padding: 8px 12px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#addTaskBtn:hover {
background-color: #218838;
}

 background-color: #28a745; → Green background.


 color: white; → White text.
 border: none; → Removes border.
 cursor: pointer; → Changes cursor to a pointer when hovering.
 hover → Changes background color to a darker green on hover.
✅ ul Styling

ul {
list-style-type: none;
padding: 0;
}

 list-style-type: none; → Removes bullet points.


 padding: 0; → Removes default padding.

✅ li Styling

li {
padding: 8px;
background-color: #e9ecef;
margin-top: 5px;
border-radius: 4px;
}

 padding: 8px; → Adds space inside each list item.


 background-color: #e9ecef; → Light gray background.
 margin-top: 5px; → Adds space between tasks.
 border-radius: 4px; → Rounds the corners.

5. <body> Section

Contains the page content and user interface.

✅ Heading

<h1>Task Manager</h1>

Displays the heading "Task Manager".

✅ Input Box

<input type="text" id="taskInput" placeholder="Enter a task..." />

 type="text" → Defines it as a text input.


 id="taskInput" → Gives it an ID to reference in JavaScript.
 placeholder="Enter a task..." → Displays a hint inside the input box.
✅ Button

<button id="addTaskBtn">Add Task</button>

 id="addTaskBtn" → Allows reference in JavaScript.

✅ Task List

<ul id="taskList"></ul>

 id="taskList" → Empty list to store tasks.

🎯 JavaScript Explanation

1. Get References to Elements


const taskInput = document.getElementById('taskInput');
const addTaskBtn = document.getElementById('addTaskBtn');
const taskList = document.getElementById('taskList');

 document.getElementById() → Accesses elements by their id.


 taskInput, addTaskBtn, and taskList store references to these elements.

2. Create addTask() Function


function addTask() {
const task = taskInput.value.trim();

if (task !== '') {


const listItem = document.createElement('li');
listItem.innerText = task;

taskList.appendChild(listItem);

taskInput.value = '';
} else {
alert("Please enter a valid task.");
}
}

1. taskInput.value.trim() → Gets user input and removes whitespace.


2. if (task !== '') → Ensures the input is not empty.
3. createElement('li') → Creates a new <li> element.
4. innerText = task → Sets task text.
5. appendChild() → Adds the task to the list.
6. taskInput.value = '' → Clears the input box.
3. Add Event Listener to Button
addTaskBtn.addEventListener('click', addTask);

 addEventListener() → Attaches a click event to the button.


 Calls addTask() when clicked.

4. Add "Enter" Key Support


taskInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
addTask();
}
});

 Listens for the Enter key press.


 Calls addTask() when pressed.

✅ How DOM Manipulation Works

1. createElement('li') → Creates a new element.


2. innerText → Sets the element's content.
3. appendChild() → Adds the element to the DOM.
4. getElementById() → Selects elements by ID.
5. addEventListener() → Listens for user actions.

4. You are developing a budgeting tool for a personal finance web app. Write a
JavaScript program that defines a global variable for income, a function
calculateBalance() that takes an expense amount, validates it using another function,
and then calculates and displays the remaining balance. Also, explain how functions
are defined in JavaScript, the concept of scope rules (global and local), and the role of
global functions in a program.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Budgeting Tool</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 20px;
}
h1 {
color: #333;
}
input, button {
padding: 8px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #28a745;
color: white;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
#balance {
margin-top: 20px;
font-size: 18px;
color: #333;
}
</style>
</head>
<body>

<h1>Personal Finance - Budgeting Tool</h1>

<!-- User Input Fields -->


<label for="income">Enter Your Income:</label>
<input type="number" id="income" placeholder="Enter income..." />
<button onclick="setIncome()">Set Income</button>
<br>

<label for="expense">Enter an Expense:</label>


<input type="number" id="expense" placeholder="Enter expense..." />
<button onclick="calculateBalance()">Add Expense</button>

<!-- Display Remaining Balance -->


<div id="balance">Remaining Balance: $0</div>

<script>
// Global variable for income (accessible throughout the program)
let totalIncome = 0;

// Function to set income


function setIncome() {
const incomeInput = document.getElementById('income').value;
if (validateAmount(incomeInput)) {
totalIncome = parseFloat(incomeInput);
updateBalance(); // Update balance display after setting income
} else {
alert("Invalid income. Please enter a positive number.");
}
}

// Function to calculate and update the balance


function calculateBalance() {
const expenseInput = document.getElementById('expense').value;
if (validateAmount(expenseInput)) {
const expense = parseFloat(expenseInput);
if (expense <= totalIncome) {
totalIncome -= expense; // Subtract the expense from income
updateBalance(); // Update balance display
} else {
alert("Expense exceeds available balance!");
}
} else {
alert("Invalid expense. Please enter a positive number.");
}
}

// Function to validate the amount (checks if positive)


function validateAmount(amount) {
return !isNaN(amount) && parseFloat(amount) > 0;
}

// Function to update the balance on the page


function updateBalance() {
document.getElementById('balance').innerText = `Remaining Balance: $$
{totalIncome.toFixed(2)}`;
}
</script>

</body
Explanation

Concepts Explained:

1. Functions in JavaScript

Functions are defined using the function keyword:

function functionName(parameters) {
// code block
}

 Functions can take parameters and return a value (optional).


 Functions are reusable and help keep the code organized.

2. Global vs Local Scope

Type Definition Example

Global Variables defined outside a function can be


let totalIncome = 0;
Scope accessed from anywhere in the program.

Local Variables defined inside a function are const expense =


Scope accessible only within that function. parseFloat(expenseInput);

Example:

let globalVar = 100; // Global variable

function testScope() {
let localVar = 50; // Local variable
console.log(globalVar); // ✅ Accessible
console.log(localVar); // ✅ Accessible inside the function
}

console.log(globalVar); // ✅ Accessible
console.log(localVar); // ❌ Error! localVar is not defined globally

3. Role of Global Functions

Global functions:

 Can be accessed from any part of the program.


 Help in managing shared data (like totalIncome).
 Can be triggered by events (like button clicks).

You might also like