Adv WT Exp

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

Advance Web Technology

Lab Experiments

Bachelor of Computer Application

Submitted by

Name: Jahanvi Singh SAP ID:


500123615

Submitted to

Dr. Nitika Nigam

University of Petroleum & Energy Studies

Bidholi, Via Prem Nagar, Dehradun, Uttarakhand

2024
Experiment 1

1. Write a jQuery to disable the right click menu in html page.


<html>
<head>
<title>Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).bind("contextmenu", function (e) { return false; });
</script>
</head>

<body>
</body>

</html>

Output:

(Right-click disabled)

2. Write a jQuery to click on a image to scroll to the top of the page.


<html>

<head>
<title>Scroll to top</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('img').click(function () {
$('html, body').animate({ scrollTop: 0 }, 'slow');
return false;
});
});
</script>
</head>

<body>
<br><br><br><br><br><br><br><br>
<h1 style="text-align: center;"><u>Click on image to scroll to
the top!</u></h1>
<br><br><br><br><br><br><br><br><br><br>
<img width="850px" height="600px" src="1.jpg" alt="">
</body>

</html>

Output:
3. Write a jQuery to change the color of any paragraph to red on mouseover
event.
<html>

<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#p1").hover(
function () {
$(this).css("color", "red");
}
)
}
);
</script>
</head>

<body>
<h1>WELCOME</h1>
<p id="p1">jQuery</p>
<p>Selectors</p>
<p>Example of Selectors</p>
<p>"*" Selector</p>
</body>

</html>

Output:

4. Display and hide message shown in the div tag on click of the buttons.
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#message").show();
});

$("#hide").click(function(){
$("#message").hide();
});
});
</script>
</head>
<body>

<h2>Show/Hide Example</h2>
<button id="show">Show Message</button>
<button id="hide">Hide Message</button>

<div id="message" style="display:none; margin-top: 20px;">


<p>This is a message inside a div element.</p>
</div>

</body>
</html>

Output:

Experiment 2

1. Write a jQuery to add a class to an element.


<html>

<head>
<title>Add class to element</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>

<script>
$(document).ready(function () {
$("button").click(function () {
$("p").addClass("class");
})
})
</script>
<style>
.class {
background-color: blueviolet;
font-style: italic;
font-size: larger;
}
</style>
</head>

<body>
<p>Add class to the element!</p>
<button>Add class</button>
</body>

</html>

Output:

2. Write a jQuery to access the position of an element.


<html>

<head>
<title>Access position of element</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
let left = $("p").position().left;
let top = $("p").position().top;
alert(`Left: ${left}, top: ${top}`);
});
})
</script>
</head>
<body>
<p>Birds are flying high</p>
<button>Access position</button>
</body>

</html>

Output:

3. Create a jQuery animation to manipulate multiple CSS properties like


padding, color etc.
<html>

<head>
<title>Manipulate CSS properties</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").animate({
padding: '50px',
marginLeft: '60px',
opacity: 0.5,
}, 1000);
});
})
</script>
</head>

<body>
<p style="font-size: 40px; font-style: italic;">Animate the
element</p>
<button>Animate</button>
</body>

</html>

Output:

Experiment 3

Use AngularJS Tables to perform the following.

• Display a Table

• Display contents of table with Order by Filter

• Display Table with even and odd.


<html>

<head>
<title>Table</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js
"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.leaders = [{ sap: "1", name: "A" }, { sap: "2", name:
"B" }, { sap: "3", name: "C" }, { sap: "4", name: "D" }]
});
</script>
</head>

<body>
<div ng-app="myApp" ng-controller="myCtrl">
<table style="background-color: antiquewhite;">
<tr>
<th>Sap Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="l in leaders">
<td>{{l.sap}}</td>
<td>{{l.name}}</td>
</tr>
</table>
<br><br>
<table style="background-color: antiquewhite;">
<tr>
<th>Sap Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="l in leaders" ng-if="l.sap > 2">
<td>{{l.sap}}</td>
<td>{{l.name}}</td>
</tr>
</table>
<br><br>
<table style="background-color: antiquewhite;">
<tr>
<th>Sap Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="l in leaders" ng-if="l.sap % 2 != 0">
<td>{{l.sap}}</td>
<td>{{l.name}}</td>
</tr>
</table>

</div>
</body>

</html>
Output:

Experiment 4

1. Create a user registration form and perform input validation using angular
JS.
<html ng-app="myApp">

<head>
<title>Registration Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
"></script>
<script>
var app = angular.module("myApp", []);
app.controller("Myctrl", function ($scope) {
$scope.name = "";
$scope.email = "";
$scope.contact = "";

});
</script>
</head>

<body>
<div ng-controller="Myctrl">
<form name="myForm">
<h2><u>Registration form</u></h2><br>
Name: <input type="text" name="name" ng-model="name"
required><br>
<label ng-if="!myForm.name.$valid" style="color:
brown;">Insert name!</label><br><br>

E-mail: <input type="email" name="email" ng-model="email"


required><br><br>
<label ng-if="!myForm.email.$valid" style="color:
brown;">Insert valid E-mail!</label><br><br>

Age: <input type="number" name="" id=""><br><br>


Gender:<br>Male <input type="radio" name="gender">Female
<input type="radio" name="gender">Other <input
type="radio" name="gender"><br><br>

Contact: <input type="number" name="contact" ng-


model="contact" required><br><br>
<label ng-if="!myForm.contact.$valid ||
contact.toString().length != 10" style="color: brown;">Insert contact
info!</label><br><br>

<button type="submit">Submit</button>
</form>
</div>
</body>

</html>

Output:
2. Create an application for Bill Payment Record using AngularJS.
<html ng-app="ngApp">

<head>
<title>Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js
"></script>

<script>
var app = angular.module("ngApp", []);
app.controller("myCtrl", function ($scope) {

$scope.list = [];
$scope.add = function () {
$scope.list.push({
name: $scope.name,
amount: $scope.amount,
date: $scope.date
});
}

$scope.delete = function (index) {


$scope.list.splice(index, 1);
}
});
</script>

</head>

<body ng-controller="myCtrl">
<div>
<input class="inp" type="text" placeholder="Name" ng-
model="name">
<input class="inp" type="number" placeholder="Amount" ng-
model="amount">
<input class="inp" type="date" placeholder="Date" ng-
model="date">
<button class="inp" ng-click="add()">Add</button>
</div><br><br>

<div style="border: dotted;">


<table style="width: 100%; text-align: center;">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Date</th>
<th>Action</th>
</tr>
<tr ng-repeat="data in list">
<td>{{ data.name }}</td>
<td>{{ data.amount }}</td>
<td>{{ data.date }}</td>
<td><button style="background-color: red;" ng-
click="delete($index)">Delete</button></td>
</tr>
</table>
</div>
</body>

</html>

Output:
Experiment 5 & 6

1. Create a simple “Hello, World!” server using Node.js and Express.


const express = require('express');

var app = express();

app.get('/', (req, res) => {


res.send("<h1>Hello World<h1>");
});

app.listen(8080, ()=> {
console.log("Listening on port 8080");
});

Output:

2. Write a node.js program to replace two or more a’s with the letter b on the
given string using Regular Expression.
const express = require('express');
const app = express();

app.get('/', (req, res) => {


const inputString = req.query.string || '';
const regex = /a{2,}/g;
const result = inputString.replace(regex, 'b');
res.send(`Replaced: ${result}`);
});
app.listen(8080, () => {
console.log(`Server running on port 8080`);
});

Output:

3. Create a basic calculator that can perform arithmetic operations (addition,


subtraction, multiplication, and division) through HTTP requests.

html
<!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>
<form action="http://127.0.0.1:8080/operation" method="POST">
Number 1: <input type="number" name="num1"> <br><br>
Number 2: <input type="number" name="num2"> <br><br>

<select name="opp" required>


<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<br><br>
<input type="submit">

</form>
</body>
</html>

Node.js
const express = require('express');
const bodyparser = require('body-parser');

const app = express();


app.use(bodyparser.urlencoded({ extended: true }));

app.post('/operation', (req, res) => {


const num1 = +req.body.num1;
const num2 = +req.body.num2;
const operator = req.body.opp;

switch (operator) {

case '+':
res.send(`<h1>Sum is ${num1 + num2}<h1>`);
break;
case '-':
res.send(`<h1>Difference is ${num1 - num2}<h1>`);
break;
case '*':
res.send(`<h1>Product is ${num1 * num2}<h1>`);
break;
case '/':
res.send(`Dividend is ${num1 / num2}<h1>`);
break;
}

});

app.listen(8080, () => {
console.log(`Server running on port 8080`);
});

Output:
4. Write a node.js code to iterate over the given array.
var arr = [1, 2, 3, 4, 5];

for (var i=0; i < arr.length; i++)


console.log(arr[i]);

Output:
Experiment 7

1. Write a program to show session management using node.js.


const express = require("express");
const session = require("express-session");
const coookieParser = require("cookie-parser");

const app = express();


const port = 3000;

app.use(coookieParser());

app.use(session({
secret: "Das ist eine password",
saveUninitialized: true,
resave: true
}));

app.get('/', (req, res) => {


if (req.session.counter) {
++req.session.counter;
return res.send(`<h1>This page has been opened $
{req.session.counter} times<h1>`);
}
else {
req.session.counter = 1;
return res.send("<h1>Welcome to our page!<h1>");
}
});

app.get("/", (req, res) => res.send("Hello World!"));


app.listen(port, () => console.log(`Example app listening on port $
{port}!`));

Output:
2. Write code to show methods for creating and destroying a session.
const express = require("express");
const session = require("express-session");

const app = express();


const PORT = 3000;

app.use(
session({
secret: "Password",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 600000000,
},
})
);

app.get("/create-session", (req, res) => {


req.session.user = { username: req.query.name, email:
req.query.email };
res.send(
`<h1>Session created successfully!<h1><br><h1><a
href='http://127.0.0.1:3000/get-session'>Visit this page to see session
data<a><h1>`
);
});

app.get("/get-session", (req, res) => {


if (req.session.user) {
res.send(
`<h1>Session Data: ${JSON.stringify(
req.session.user
)}<h1><br><h1><a href='http://127.0.0.1:3000/destroy-session'>Visit
this page to destroy session data<a><h1><h1>`
);
} else {
res.send("No session data found.");
}
});

app.get("/destroy-session", (req, res) => {


req.session.destroy();
return res.send(`<h1>Session destroyed successfully<h1>`);
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Output:

3. Write a program to create and delete a cookie using nodejs.


const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());

app.get('/create-cookie', (req, res) => {

res.cookie('myCookie', { maxAge: 10000000 });


res.send('<h1>Cookie has been created!<h1>');
});

app.get('/delete-cookie', (req, res) => {

res.clearCookie('myCookie');
res.send('<h1>Cookie has been deleted!<h1>');
});

app.get('/check-cookie', (req, res) => {

if (req.cookies.myCookie) {
res.send(`<h1>Cookie found: ${req.cookies.myCookie}<h1>`);
} else {
res.send('<h1>No cookie found.<h1>');
}
});

const PORT = 3000;


app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Output:
Experiment 8

1. Create a NodeJS application to connect to a MongoDB database.


const mongoose = require('mongoose');

const uri = 'mongodb://localhost:27017/database';

mongoose.connect(uri);

const db = mongoose.connection;

db.on('connected', () => {
console.log('Connected to MongoDB successfully!');
});

db.on('error', (error) => {


console.error('Unable to connect to MongoDB:', error);
});

Output:

2. Create an application to store the details of students in a database.

3. Create a search application for finding the students based on given search
criteria.
const mongoose = require("mongoose");
const express = require("express");

const app = express();


const uri = "mongodb://localhost:27017/database";

mongoose
.connect(uri)
.then(() => {
console.log("Connected to MongoDB successfully!");
})
.catch((error) => {
console.error("Unable to connect to MongoDB:", error);
});

students = mongoose.connection.collection("students");

app.get("/add-student", async (req, res) => {


const { name, sap } = req.query;

if (!name && !sap) {


return res.send(`<h1>add 'name' AND 'sap' in parameter in the
url<h1>`);
}

const result = await students.insertOne({ name: name, sap: sap });


return res.send("<h1>Student added successfully!<h1>");
});

app.get("/find-student", async (req, res) => {


const { name, sap } = req.query;

if (name && !sap) {


const result = await students.findOne({ name: name });
if (result) {
return res.send(
`<h1> Student Exists <br>name: ${result.name}<br>sap: $
{result.sap}<h1>`
);
} else {
return res.send(`<h1>Student does not exist<h1>`);
}
} else if (sap && !name) {
const result = await students.findOne({ name: name });
if (result) {
return res.send(
`<h1> Student Exists <br>name: ${result.name}<br>sap: $
{result.sap}<h1>`
);
} else {
return res.send(`<h1>Student does not exist<h1>`);
}
} else if (sap && name) {
const result = await students.findOne({ name: name, sap: sap });
if (result) {
return res.send(
`<h1> Student Exists <br>name: ${result.name}<br>sap: $
{result.sap}<h1>`
);
} else {
return res.send(`<h1>Student does not exist<h1>`);
}
} else {
return res.send(`<h1>add 'name' OR 'sap' in parameter of the
url<h1>`);
}
});

app.listen(3000, () => {
console.log("Sever is running on port 3000");
});

Output:
4. Write a program to create an application for a shopping center with all the
facilities like add an item, delete an item, update an item detail, stock report,
sale etc.

const express = require("express");


const mongoose = require("mongoose");

const app = express();


const PORT = 3000;

const MONGO_URI = "mongodb://localhost:27017/shoppingCenter";


mongoose.connect(MONGO_URI);
const db = mongoose.connection;

db.on("error", console.error.bind(console, "Connection error:"));


db.once("open", () => {
console.log("Connected to MongoDB");
});
const itemsCollection = db.collection("items");

app.get("/add-item", async (req, res) => {


const { name, price, stock } = req.query;

if (!name || !price || !stock) {


return res.send(`<h1>Provide 'name', 'price', and 'stock' as
parameters in the URL</h1>`);
}

const result = await itemsCollection.insertOne({


name,
price: parseFloat(price),
stock: parseInt(stock),
});
return res.send("<h1>Item added successfully!</h1>");
});

app.get("/delete-item", async (req, res) => {


const { name } = req.query;

if (!name) {
return res.send(`<h1>Provide 'name' as a parameter in the URL</h1>`);
}

const result = await itemsCollection.deleteOne({ name });


if (result.deletedCount === 0) {
return res.send("<h1>Item not found!</h1>");
}

return res.send("<h1>Item deleted successfully!</h1>");


});

app.get("/update-item", async (req, res) => {


const { name, price, stock } = req.query;

if (!name || (!price && !stock)) {


return res.send(
`<h1>Provide 'name' and at least one of 'price' or 'stock' as
parameters in the URL</h1>`
);
}
const update = {};
if (price) update.price = parseFloat(price);
if (stock) update.stock = parseInt(stock);

const result = await itemsCollection.updateOne({ name }, { $set: update


});

if (result.matchedCount === 0) {
return res.send("<h1>Item not found!</h1>");
}

return res.send("<h1>Item updated successfully!</h1>");


});

app.get("/stock-report", async (req, res) => {


const items = await itemsCollection.find().toArray();
if (items.length === 0) {
return res.send("<h1>No items in stock!</h1>");
}

const report = items


.map((item) => `<p>${item.name}: ${item.stock} units</p>`)
.join("");
return res.send(`<h1>Stock Report</h1>${report}`);
});

app.get("/record-sale", async (req, res) => {


const { name, quantity } = req.query;

if (!name || !quantity) {
return res.send(`<h1>Provide 'name' and 'quantity' as parameters in
the URL</h1>`);
}

const item = await itemsCollection.findOne({ name });

if (!item) {
return res.send("<h1>Item not found!</h1>");
}

if (item.stock < parseInt(quantity)) {


return res.send("<h1>Insufficient stock!</h1>");
}

const newStock = item.stock - parseInt(quantity);


await itemsCollection.updateOne({ name }, { $set: { stock:
newStock } });

return res.send("<h1>Sale recorded successfully!</h1>");


});

app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Output:
Experiment 9&10

1. Create a bar chart using SVG and d3.js.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<title>D3.js Bar Chart</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: orange;
}
.axis text {
font-size: 12px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<h1>D3.js Bar Chart Example</h1>
<svg id="chart" width="600" height="400"></svg>
<script>
const data = [25, 30, 45, 60, 20, 65, 75];

const width = 600;


const height = 400;
const margin = { top: 20, right: 30, bottom: 30, left: 40 };

const svg = d3
.select("#chart")
.attr("width", width)
.attr("height", height);

const xScale = d3
.scaleBand()
.domain(data.map((d, i) => i))
.range([margin.left, width - margin.right])
.padding(0.1);

const yScale = d3
.scaleLinear()
.domain([0, d3.max(data)])
.nice()
.range([height - margin.bottom, margin.top]);

const xAxis = d3.axisBottom(xScale).tickFormat((d, i) => `Item ${i


+ 1}`);
const yAxis = d3.axisLeft(yScale);

svg
.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(xAxis);

svg
.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(yAxis);

svg
.selectAll(".bar")
.data(data)
.join("rect")
.attr("class", "bar")
.attr("x", (d, i) => xScale(i))
.attr("y", (d) => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", (d) => yScale(0) - yScale(d));
</script>
</body>
</html>
Output:

2. Create circles and rectangles into interactive controls using SVG and D3.js.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<title>Simple Interactive SVG</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.shape {
cursor: pointer;
stroke: black;
stroke-width: 2px;
}
.circle {
fill: lightblue;
}
.rectangle {
fill: lightgreen;
}
</style>
</head>
<body>
<h1>Interactive SVG Shapes</h1>
<svg
id="svg-canvas"
width="600"
height="400"
style="border: 1px solid black"
></svg>
<script>
const svg = d3.select("#svg-canvas");

const shapes = [
{ type: "circle", cx: 100, cy: 100, r: 30 },
{ type: "rectangle", x: 200, y: 150, width: 80, height: 60 },
];

shapes.forEach((shape) => {
if (shape.type === "circle") {
svg
.append("circle")
.attr("class", "shape circle")
.attr("cx", shape.cx)
.attr("cy", shape.cy)
.attr("r", shape.r)
.call(
d3.drag().on("drag", function (event) {
d3.select(this)
.attr("cx", (shape.cx = event.x))
.attr("cy", (shape.cy = event.y));
})
);
} else if (shape.type === "rectangle") {
svg
.append("rect")
.attr("class", "shape rectangle")
.attr("x", shape.x)
.attr("y", shape.y)
.attr("width", shape.width)
.attr("height", shape.height)
.call(
d3.drag().on("drag", function (event) {
d3.select(this)
.attr("x", (shape.x = event.x - shape.width / 2))
.attr("y", (shape.y = event.y - shape.height / 2));
})
);
}
});
</script>
</body>
</html>

Output:

3. Write a code to select a particular element and modify the properties


using D3.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Modify SVG Element with D3</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.shape {
stroke: black;
stroke-width: 2px;
}
</style>
</head>
<body>
<h1>Modify SVG Element Using D3.js</h1>
<button id="modify-circle">Change Circle</button>
<button id="modify-rect">Change Rectangle</button>
<svg id="svg-canvas" width="400" height="300" style="border: 1px
solid black;">
<circle class="shape" id="my-circle" cx="100" cy="100" r="50"
fill="lightblue"></circle>
<rect class="shape" id="my-rect" x="200" y="50" width="80"
height="60" fill="lightgreen"></rect>
</svg>
<script>

d3.select("#modify-circle").on("click", () => {
d3.select("#my-circle")
.attr("fill", "orange")
.attr("r", 70)
.attr("cx", 150);
});

d3.select("#modify-rect").on("click", () => {
d3.select("#my-rect")
.attr("fill", "purple")
.attr("width", 100)
.attr("x", 250);
});
</script>
</body>
</html>

Output:
4. Create an application to fetch data from csv file and populate a graph
using SVG and D3.

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>CSV Data to Graph</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: orange;
}
.axis path,
.axis line {
stroke: black;
}
</style>
</head>
<body>
<h1>CSV to Bar Graph</h1>
<svg id="chart" width="600" height="400"></svg>
<script>
const width = 600;
const height = 400;
const margin = { top: 20, right: 30, bottom: 30, left: 40 };
d3.csv("data.csv").then(data => {
data.forEach(d => {
d.value = +d.value;
});

const xScale = d3.scaleBand()


.domain(data.map(d => d.category))
.range([margin.left, width - margin.right])
.padding(0.1);

const yScale = d3.scaleLinear()


.domain([0, d3.max(data, d => d.value)])
.nice()
.range([height - margin.bottom, margin.top]);

const svg = d3.select("#chart");

svg.selectAll(".bar")
.data(data)
.join("rect")
.attr("class", "bar")
.attr("x", d => xScale(d.category))
.attr("y", d => yScale(d.value))
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(0) - yScale(d.value));

svg.append("g")
.attr("transform", `translate(0,${height -
margin.bottom})`)
.call(d3.axisBottom(xScale));

svg.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale));
}).catch(error => {
console.error("Error loading the CSV data:", error);
});
</script>
</body>
</html>

Output:

You might also like