JSFiddle - React, Tailwind, and code Playground
by Saurabh Khemka
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<table id="myTable">
<thead>
<td class="tal">Account</td>
<td class="tar" id="change" direction="asc">Available Cash<br /><label class="header">Today's change</label></td>
</thead>
</table>
<span id="load" direction="more">Load more</span>
<script src="js/main.js"></script>
</body>
</html>
CSS
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td {
border: 1px solid #dddddd;
padding: 8px;
}
.tal {
text-align: left;
}
.tar {
text-align: right;
}
.name {
font-weight: bold;
color: blue;
}
.positive .price {
color: green;
}
.negative .price {
color: red;
}
.header {
font-weight: normal;
font-size: 12px;
cursor: pointer;
}
#load {
color: blue;
text-align: center;
padding-top: 20px;
display: block;
cursor: pointer;
}
JavaScript
let stocks = [{
id: 5200,
name: 'IRA',
price: 5763.36,
currValue: 8916.69
},
{
id: 1812,
name: 'AAA',
price: 2010926.10,
currValue: 2000456.55
},
{
id: 3434,
name: 'DAA',
price: 2323.10,
currValue: 3435.55
}
];
stocks.forEach(function(s) {
let difference = s.currValue - s.price;
s.diff = difference;
s.percentDiff = ((((difference / s.currValue) * 100) * 100) / 100).toFixed(2);
});
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
function sortBy(prop, dir) {
return function(a, b) {
return a[prop] == b[prop] ? 0 : (dir == 'asc' ? (a[prop] < b[prop] ? -1 : 1) : (a[prop] > b[prop] ? -1 : 1))
}
}
addTable(stocks);
var elem = document.getElementById('change');
var elem1 = document.getElementById('load');
elem.addEventListener("click", function() {
direction = elem.getAttribute('direction') === 'asc' ? 'desc' : 'asc';
elem.setAttribute('direction', direction);
stocks.sort(sortBy('diff', direction));
document.getElementById('tbody').remove();
addTable(stocks);
});
elem1.addEventListener("click", function() {
direction = elem1.getAttribute('direction') === 'more' ? 'less' : 'more';
elem1.setAttribute('direction', direction);
elem1.innerHTML = 'Load ' + direction;
document.getElementById('tbody').remove();
addTable(stocks);
});
function addTable(stockArr) {
var tableDiv = document.getElementById("myTable");
var tbody = document.createElement('tbody');
tbody.id = "tbody";
for (var i = 0; i < stockArr.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.innerHTML = '<label class="name tal">' + stockArr[i].name + ' - ' + stockArr[i].id + '</label>';
td2.classList.add(stockArr[i].diff > 0 ? 'positive' : 'negative');
td2.classList.add('tar');
td2.innerHTML = '<label>' +...