Creating Sorting List in JavaScript
Creating a sorting list in JavaScript that sorting a list in alphabetically ascending order. A sorting button will would make on the top of of list and given country name in out of order list whenever a user click on the sorting button the JavaScript code will be sorting the country list in order.
HTML of Sorting List
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sorting</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Javascript Alphabatically Sorting List</h1>
<p>Sort the given country list Alphabatically by one click</p>
<div class="main">
<button onclick="sortList()">Sorting</button>
</div>
<div class="list">
<ul id="id01">
<li>India</li>
<li>Germany</li>
<li>France</li>
<li>UAE</li>
<li>Russia</li>
<li>China</li>
<li>Japan</li>
<li>United State</li>
<li>Alabania</li>
<li>United kinkdom</li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS of Sorting List
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: rgb(13, 13, 128);
align-items: center;
justify-content: center;
display: flex;
}
.container {
display: block;
align-items: center;
justify-content: center;
box-shadow: 0 0 30px 0 #fff;
font-family: sans-serif;
font-weight: 600;
height: auto;
color: #fff;
border-radius: 20px;
padding: 20px;
margin: 20px;
}
.container h1 {
font-size: 24px;
padding: 8px;
}
.container button {
padding: 15px 50px;
margin: 10px;
font-family: sans-serif;
font-weight: 600;
cursor: pointer;
box-shadow: 0 0 30px 0 #fff;
text-align: center;
font-size: 20px;
border-radius: 50px;
border: none;
outline: none;
}
.container p {
color: green;
font-size: 18px;
margin-bottom: 6px;
}
.container ul {
margin: 10px;
padding: 10px;
font-family: sans-serif;
align-items: center;
}
.container li {
font-family: sans-serif;
font-size: 14px;
font-weight: 500;
padding: 5px;
}
JavaScript of Sorting List
function sortList() {
var list, i, switching, b, shouldswitch;
list = document.getElementById("id01");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for(i = 0; i < (b.length-1); i++) {
shouldswitch = false;
if (b[i].innerHTML.toLowerCase() >b[i + 1].innerHTML.toLowerCase()) {
shouldswitch = true;
break;
}
}
if (shouldswitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
For more details watch the complete video
Comments
Post a Comment