Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Web Scripting Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Web Scripting Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Department of Computer Science & Engineering

LAB MANUAL

B.Tech. (Computer Science and Engineering)

Subject Name : - Web Scripting Lab

Subject Code : - CS289

INTEGRAL UNIVERSITY LUCKNOW


Dasauli, Kursi Road, PO Basha-226026
Experiment No. Name Of Experiment

Write a JavaScript program to display the current day and time in the
1 following format. Sample Output:
Today is: Tuesday. Currently time is: 10 PM: 30:38

Write a program to redirect, popup and print function in JavaScript


2

Write a JavaScript program to change background color after 5 seconds of


3
page load.

Write a JavaScript program to dynamically bold, Italic, Underline words


4
and phrases based on user action

Write a java script program to display a hidden div (e.g. showing stats of
5
a player when user clicks on his name)

6 Write a JavaScript program to check the given number is mobile number


or not using form

Write a JavaScript program to test the first character of a string is


7
uppercase or not

8 Create a Simple Login form using ReactJS.

WAP to create a simple calculator Application using ReactJS.


9

10 WAP to create a voting application using ReactJS.


VISION
To produce highly skilled personnel who are empowered enough to transform the society by their
education, research and innovations.

MISSION
 To offer diverse academic programs at undergraduate, postgraduate, and doctorate levels that are in line
with the current trends in Computer Science and Engineering.
 To provide the state-of-the-art infrastructure for teaching, learning and research.
 To facilitate collaborations with other universities, industry and research labs.

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)

B Tech: Computer Science & Engineering

PEO1 To produce graduates who have strong foundation of knowledge and skills in the field of computer
science and engineering.

PEO2 To produce graduates who are employable in industries/public sector/research organizations or work
as an entrepreneur.

PEO3 To produce graduates who can provide solutions to challenging problems in their profession by
applying computer engineering theory and practices.

PEO4 To produce graduates who can provide leadership and are effective in multidisciplinary environment

PROGRAM SPECIFIC OUTCOMES (PSO’s)

Ability to understand the principles and working of computer systems. Students


PSO 1 have a sound knowledge about the hardware and software aspects of computer
systems.
Ability to design and develop computer programs and understand the structure
PSO 2 and development methodologies of software systems.
Ability to apply their skills in the field of algorithms, networking, web design,
PSO 3 cloud computing and data analytics.
Ability to apply knowledge to provide innovative novel solutions to existing
PSO 4 problem and identify research gaps.
Program Outcomes (PO)

PO's

 PO1: Ability to apply knowledge of science, computing and mathematics to deal with computer
engineering problems.
 PO2: Ability to analyze the computer engineering problems, formulate them in order to achieve the
solution.
 PO3: Ability to develop and design solutions based on analysis to solve engineering problems.
 PO4: Ability to handle complex and interdisciplinary engineering problems by using their research
methodology.
 PO5: Ability to apply state of the art tools and techniques in order to achieve economic solutions to the
problems.
 PO6: Ability of being aware about the existing social problems and keen to find their solutions by using
their computer engineering skills.
 PO7: Ability to provide environment friendly and sustainable solutions.
 PO8: Ability to understand their professional and ethical responsibility.
 PO9: Ability to work as an individual as well as in teams.
 PO10: Ability to communicate with the stake holders by applying their soft skills.
 PO11: Ability to manage the day-to-day challenges by optimizing the project resources.
 PO12: Ability to engage and encourage themselves in continuous learning process in order to cope up
with the rapidly growing tools and technology.

Course outcome

1. Understand the role of java script in web development.


2. Syntax and structure of JavaScript code.
3. Java Scripts to solve real world problems.
4. Utilize the Concepts of JavaScript.
5. React JS concepts to solve real world problems.
JavaScript Introduction:

JavaScript (often abbreviated as JS) is a programming language that along with HTML and CSS, is considered
one of the core technologies of the web. It's what makes web pages interactive and dynamic.

On the other hand, JavaScript is used to make Web pages interactive and is a markup language heavily used for
building web apps.

History of JavaScript:

JavaScript started life as LiveScript, but Netscape changed the name, possibly because of the excitement being
generated by Java.to JavaScript. JavaScript made its first appearance in Netscape 2.0 in 1995 with a name
LiveScript.

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you
to build interactivity into otherwise static HTML pages.
JavaScript is:

JavaScript is a lightweight, interpreted programming language


• Designed for creating network-centric applications
• Complementary to and integrated with Java
• Complementary to and integrated with HTML
• Open and cross-platform

Client-side JavaScript:
Client-side JavaScript is the most common form of the language. The script should be included in or referenced
by an HTML document for the code to be interpreted by the browser.
It means that a web page need no longer be static HTML, but can include programs that interact with the user,
control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism features many advantages over traditional CGI server-side scripts. For
example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would
be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that
the user explicitly or implicitly initiates.

Advantages of JavaScript:

The merits of using JavaScript are:

Less server interaction: You can validate user input before sending the page off to the server. This saves server
traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to enter
something.
Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or
activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a
Rich Interface to your site visitors.

Limitations with JavaScript:

We can not treat JavaScript as a full-fledged programming language. It lacks the following important features:
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reasons.
JavaScript can not be used for Networking applications because no such support is available.
JavaScript doesn't have any multithreading or multiprocess capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity
into otherwise static HTML pages.
JavaScript Development Tools:
One of JavaScript's strengths is that expensive development tools are not usually required. You can start with a
simple text editor such as Notepad.
Since it is an interpreted language inside the context of a web browser, you don't even need to buy a compiler.

Various vendors have come up with very nice JavaScript editing tools to simplify our lives. A few of them are
listed here:

Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of an
interactive website.
Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML and JavaScript
editor in the professional web development crowd.
It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new
standards such as XHTML and XML.
Macromedia HomeSite 5: This provides a well-liked HTML and JavaScript editor, which will manage their
personal website just fine.

JavaScript Syntax

JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web
page.
You can place the <script> tag containing your JavaScript anywhere within your web page, but it is preferred to
keep it within the <head> tags. 28

The <script> tag alerts the browser program to interpret all the text between these tags as a script. So, the simple
syntax of your JavaScript will be as follows

<script ...>
JavaScript code
</script>
The script tag takes two important attributes:

language: This attribute specifies what scripting language you are using. Typically, its value will be javascript.
Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.

type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set
to "text/javascript".

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Script:

Let us write our class example to print out "Hello World".

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser
that does not support Javascript. The comment ends with a "//-->". Here "//" signifies a comment in Javascript, so we
add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.
Next, we call a function document.write which writes a string into our HTML document. This function can be used
to write text, HTML, or both. So above code will display following result:

Hello World!
Program No. -1

Write a javascript program to display the current day and time.

// Get the current date and time


let currentDate = new Date();

// Array of days
let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

// Get the day of the week


let dayOfWeek = days[currentDate.getDay()];

// Get current time


let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();

// Format hours, minutes, and seconds to ensure they have two digits
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;

// Display current day and time


console.log(`Current day and time is ${dayOfWeek} ${hours}:${minutes}:${seconds}`);

This script does the following:

1. Retrieves the current date and time using new Date().


2. Retrieves the day of the week using getDay() method, and formats it using an array of day names.
3. Retrieves the hours, minutes, and seconds from the current date object, ensuring they are formatted with
leading zeros if necessary.
4. Prints the current day and time in the format: "Current day and time is [day of the week]
[hours]:[minutes]:[seconds]".

OUTPUT: The current day and time is Friday 18:04:58


Program No -2

Write a program to redirect, popup, and print function 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 Functions</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background: #fff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h1 {
margin-bottom: 1rem;
color: #333;
}
button {
display: inline-block;
margin: 0.5rem;
padding: 0.75rem 1.5rem;
font-size: 1rem;
color: #fff;
background-color: #007bff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
button:active {
background-color: #00408a;
}
</style>
<script>
function redirect(url) {
window.location.href = url;
}
function openPopup(url, width, height) {
const popupWindow = window.open(url, 'popupWindow',
`width=${width},height=${height},scrollbars=yes`);
if (popupWindow) {
popupWindow.focus();
} else {
alert('Popup blocked. Please allow popups for this
website.');
}
}
function printPage() {
window.print();
}
</script>
</head>
<body>
<div class="container">
<h1>JavaScript Functions</h1>
<button
onclick="redirect('https://www.example.com')">Redirect to
Example.com</button>
<button onclick="openPopup('https://www.example.com', 600,
400)">Open Popup</button>
<button onclick="printPage()">Print Page</button>
</div>
</body>
</html>
OUTPUT

Redirect

Popup Print
Program No -3

Write a JavaScript program to change the background color after 5 seconds of page
load.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
<style>
/* Initial background color */
body {
background-color: #f0f0f0;
transition: background-color 1s; /* Smooth transition for the color change */
}
</style>
<script>
// Function to change background color
function changeBackgroundColor() {
// New background color
document.body.style.backgroundColor = '#3498db'; // Example color: Blue
}

// Wait for the DOM to be fully loaded


window.onload = function() {
// Change the background color after 5 seconds
setTimeout(changeBackgroundColor, 5000);
};
</script>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>Watch the background color change after 5 seconds!</p>
</body>
</html>
OUTPUT
Program No -4

Write a JavaScript program to dynamically bold, Italic, Underline words and phrases
based on user action

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Styler</title>
<style>
/* Basic styling for the page */
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f9f9f9;
}

.container {
max-width: 600px;
margin: 0 auto;
}

.input-group {
margin-bottom: 10px;
}

.input-group label {
display: block;
margin-bottom: 5px;
}

.input-group input, .input-group button {


width: 100%;
padding: 10px;
margin-bottom: 5px;
box-sizing: border-box;
}

#output {
padding: 10px;
border: 1px solid #ddd;
min-height: 50px;
background-color: #fff;
}

/* Style for active buttons */


button.active {
background-color: #007bff;
color: #fff;
}
</style>
</head>
<body>
<div class="container">
<h1>Text Styler</h1>
<div class="input-group">
<label for="textInput">Enter Text:</label>
<input type="text" id="textInput" placeholder="Enter your text here">
</div>
<div class="input-group">
<button id="boldButton">Bold</button>
<button id="italicButton">Italic</button>
<button id="underlineButton">Underline</button>
</div>
<div id="output"></div>
</div>

<script>
// Get references to DOM elements
const textInput = document.getElementById('textInput');
const boldButton = document.getElementById('boldButton');
const italicButton = document.getElementById('italicButton');
const underlineButton = document.getElementById('underlineButton');
const output = document.getElementById('output');

// Function to update the output area with the text input


function updateOutput() {
output.innerHTML = textInput.value;
}

// Function to toggle bold style


boldButton.addEventListener('click', () => {
if (textInput.value) {
if (boldButton.classList.contains('active')) {
output.innerHTML = output.innerHTML.replace(/<\/?b>/g, ''); // Remove existing <b> tags
boldButton.classList.remove('active');
} else {
output.innerHTML = `<b>${textInput.value}</b>`; // Wrap text in <b> tags
boldButton.classList.add('active');
}
}
});

// Function to toggle italic style


italicButton.addEventListener('click', () => {
if (textInput.value) {
if (italicButton.classList.contains('active')) {
output.innerHTML = output.innerHTML.replace(/<\/?i>/g, ''); // Remove existing <i> tags
italicButton.classList.remove('active');
} else {
output.innerHTML = `<i>${textInput.value}</i>`; // Wrap text in <i> tags
italicButton.classList.add('active');
}
}
});

// Function to toggle underline style


underlineButton.addEventListener('click', () => {
if (textInput.value) {
if (underlineButton.classList.contains('active')) {
output.innerHTML = output.innerHTML.replace(/<\/?u>/g, ''); // Remove existing <u> tags
underlineButton.classList.remove('active');
} else {
output.innerHTML = `<u>${textInput.value}</u>`; // Wrap text in <u> tags
underlineButton.classList.add('active');
}
}
});

// Update the output area when the user types in the text input
textInput.addEventListener('input', updateOutput);
</script>
</body>
</html>

OUTPUT

BOLD TEXT
ITALIC TEXT

UNDERLINE TEXT
Program No -5

Write a java script program to display a hidden div (e.g. showing stats of a player when
user clicks on his name)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Player Stats</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
color: #333;
padding: 2rem;
}
.player-list {
list-style: none;
padding: 0;
display: flex;
gap: 50px;
}
.player-list li {
margin: 1rem 0;
cursor: pointer;
color: #007bff;
text-decoration: underline;
}
.player-list li:hover {
color: #0056b3;
}
.stats {
display: none;
margin-top: 1rem;
padding: 1rem;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #fff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style><script>
function showStats(playerId) {
const statsDiv = document.getElementById(playerId);
if (statsDiv.style.display === "none" || statsDiv.style.display
=== "") {
statsDiv.style.display = "block";
} else {
statsDiv.style.display = "none";
}
}
</script>
</head>
<body>
<h1>Player Stats</h1>
<ul class="player-list">
<li onclick="showStats('player1-stats')">Player 1</li>
<li onclick="showStats('player2-stats')">Player 2</li>
<li onclick="showStats('player3-stats')">Player 3</li>
</ul>
<div id="player1-stats" class="stats">
<h2>Player 1 Stats</h2>
<p>Points: 25</p>
<p>Assists: 5</p>
<p>Rebounds: 10</p>
</div>
<div id="player2-stats" class="stats">
<h2>Player 2 Stats</h2>
<p>Points: 30</p>
<p>Assists: 8</p>
<p>Rebounds: 12</p>
</div>
<div id="player3-stats" class="stats">
<h2>Player 3 Stats</h2>
<p>Points: 20</p>
<p>Assists: 7</p>
<p>Rebounds: 15</p>
</div>
</body>
</html>
OUTPUT
Program No -6

Write a JavaScript program to check the given number is mobile number or not using
form

<!DOCTYPE html>
<html>
<head>
<title>Mobile Number Checker</title>
</head>
<body>
<form id="mobileForm">
<label for="mobileNumber">Enter Mobile Number:</label>
<input type="text" id="mobileNumber" name="mobileNumber">
<button type="button" onclick="checkMobileNumber()">Check</button>
</form>
<p id="result"></p>

<script>
function checkMobileNumber() {
const mobileNumber = document.getElementById("mobileNumber").value;
const mobileRegex = /^[6789]\d{9}$/; // Indian mobile number format

if (mobileRegex.test(mobileNumber)) {
document.getElementById("result").textContent = "Valid Mobile Number";
} else {
document.getElementById("result").textContent = "Invalid Mobile Number";
}
}
</script>
</body>
</html>
OUTPUT
Program No -7

Write a JavaScript program to test the first character of a string is uppercase or not

function isUpperCase(str) {
return str.length > 0 && str[0] === str[0].toUpperCase();
}

// Example usage:
const str1 = "Helo"
const str2 = "world";
const str3 = "";

console.log(isUpperCase(str1)); // Output: true


console.log(isUpperCase(str2)); // Output: false
console.log(isUpperCase(str3)); // Output: false

OUTPUT
Program No -8

Create a Simple Login form using ReactJS.

import React, { useState } from 'react';


import './App.css';
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
if (username === '' || password === '') {
setError('Both fields are required');
} else {
setError('');
alert(`Username: ${username}, Password: ${password}`);
}
};
return (
<div className="App">
<h1>Login</h1>
<form onSubmit={handleSubmit} style={styles.form}>
<div style={styles.inputGroup}>
<label style={styles.label}>Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={styles.input}
/>
</div>
<div style={styles.inputGroup}>
<label style={styles.label}>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={styles.input}
/>
</div>
{error && <p style={styles.error}>{error}</p>}
<button type="submit" style={styles.button}>
Login
</button>
</form>
</div>
);
}
const styles = {
form: {
maxWidth: '400px',
margin: '0 auto',
padding: '2rem',
border: '1px solid #ddd',
borderRadius: '4px',
backgroundColor: '#fff',
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
},
inputGroup: {
marginBottom: '1rem',
},
label: {
display: 'block',
marginBottom: '0.5rem',
fontWeight: 'bold',
},
input: {
width: '100%',
padding: '0.5rem',
border: '1px solid #ddd',
borderRadius: '4px',
},
button: {
width: '100%',
padding: '0.75rem',
border: 'none',
borderRadius: '4px',
backgroundColor: '#007bff',
color: '#fff',
fontSize: '1rem',
cursor: 'pointer',
transition: 'background-color 0.3s ease',
},
error: {
color: 'red',
marginBottom: '1rem',
},
};
export default App;

OUTPUT
Program No -9

WAP to create a simple calculator Application using ReactJS.

App.jsx
import React, { useState } from 'react';
import './App.css';
function App() {
const [display, setDisplay] = useState('0');
const [currentValue, setCurrentValue] = useState('0');
const [previousValue, setPreviousValue] = useState('');
const [operator, setOperator] = useState('');
const [waitingForOperand, setWaitingForOperand] = useState(false);
const handleButtonClick = (value) => {
if (value === 'AC') {
clearDisplay();
} else if (
value === '+' ||
value === '-' ||
value === '*' ||
value === '/'
){
handleOperator(value);
} else if (value === '=') {
calculateResult();
} else {
updateDisplay(value);
}
};
const clearDisplay = () => {
setDisplay('0');
setCurrentValue('0');
setPreviousValue('');
setOperator('');
setWaitingForOperand(false);
};
const handleOperator = (value) => {
if (operator && waitingForOperand) {
setOperator(value);
return;
}
if (previousValue === '') {
setPreviousValue(currentValue);
} else if (!waitingForOperand) {
const result = calculate(
parseFloat(previousValue),
parseFloat(currentValue),
operator
);
setPreviousValue(result);
setCurrentValue(result.toString());
setDisplay(result.toString());
}
setOperator(value);
setWaitingForOperand(true);
};
const calculateResult = () => {
if (!operator || waitingForOperand) return;
const result = calculate(
parseFloat(previousValue),
parseFloat(currentValue),
operator
);
setDisplay(result.toString());
setCurrentValue(result.toString());
setPreviousValue('');
setOperator('');
setWaitingForOperand(false);
};
const calculate = (prev, current, operator) => {
switch (operator) {
case '+':
return prev + current;
case '-':
return prev - current;
case '*':
return prev * current;
case '/':
return prev / current;
default:
return current;
}
};
const updateDisplay = (value) => {
if (value === '.' && currentValue.includes('.')) return;
if (waitingForOperand) {
setDisplay(value);
setCurrentValue(value);
setWaitingForOperand(false);
} else {
const newValue =
currentValue === '0' ? value : currentValue + value;
setDisplay(newValue);
setCurrentValue(newValue);
}
};
const Button = ({ label, orange, wide }) => {
const className = ['button', orange ? 'orange' : '', wide ? 'wide' : '']
.join(' ')
.trim();
return (
<button
className={className}
onClick={() => handleButtonClick(label)}
>
{label}
</button>
);
};
return (
<div className="App">
<h1>Simple Calculator</h1>
<div className="calculator">
<div className="display">{display}</div>
<div className="buttons">
<Button label="AC" />
<Button label="+/-" />
<Button label="%" />
<Button label="/" orange />
<Button label="7" />
<Button label="8" />
<Button label="9" />
<Button label="*" orange />
<Button label="4" />
<Button label="5" />
<Button label="6" />
<Button label="-" orange />
<Button label="1" />
<Button label="2" />
<Button label="3" />
<Button label="+" orange />
<Button label="0" wide />
<Button label="." />
<Button label="=" orange />
</div>
</div>
</div>
);
}
export default App;
App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
background-color: #f9f9f9;
padding: 20px;
}
h1 {
margin-bottom: 20px;
}
.calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #f3f3f3;
padding: 20px;
text-align: center;
}
.display {
font-size: 2rem;
background-color: #fff;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.button {
font-size: 1.5rem;
padding: 15px 0;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #e0e0e0;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #ccc;
}
.button.orange {
background-color: #ff9c00;
color: #fff;
}
.button.wide {
grid-column: span 2;
}
OUTPUT
Program No -10

WAP to create a voting application using ReactJS.

App.jsx
import React, { useState } from 'react';
import './App.css';
function App() {
const [candidates, setCandidates] = useState([
{ name: 'Candidate 1', votes: 0 },
{ name: 'Candidate 2', votes: 0 },
{ name: 'Candidate 3', votes: 0 },
]);
const voteForCandidate = (index) => {
const newCandidates = [...candidates];
newCandidates[index].votes += 1;
setCandidates(newCandidates);
};
return (
<div className="App">
<h1>Voting Application</h1>
<div className="candidates">
{candidates.map((candidate, index) => (
<div key={index} className="candidate">
<h2>{candidate.name}</h2>
<p>Votes: {candidate.votes}</p>
<button onClick={() => voteForCandidate(index)}>
Vote
</button>
</div>
))}
</div>
</div>
);
}
export default App;
App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
background-color: #f9f9f9;
padding: 20px;
}
h1 {
margin-bottom: 20px;
}
.candidates {
display: flex;
justify-content: space-around;
}
.candidate {
border: 1px solid #ccc;
border-radius: 8px;
padding: 20px;
width: 200px;
background-color: #fff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.candidate h2 {
margin: 0 0 10px 0;
}
.candidate p {
margin: 0 0 10px 0;
}
.candidate button {
padding: 10px 20px;
border: none;
border-radius: 4px;
background-color: #4CAF50;
color: white;
cursor: pointer;
transition: background-color 0.3s ease;
}
.candidate button:hover {
background-color: #45a049;
}
OUTPUT

You might also like