WebSocket: Multiple cryptos to display - javascript

I understood how to display the course of a crypto for example btc
image
The problem is that I would like to display the price of BTC and the price of ETH at the same time.
But, I don't know how to do it? I am stuck when I should add several cyptos... :S
I have my code here below:
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceElement = document.getElementById('btcStockPrice');
let lastPrice = null;
ws.onmessage = (even) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElement.innerText = price;
stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
lastPrice = price;
}
I don't know how I should add ethcusdt#trade ?
Thank you for your help and your time.
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceElement = document.getElementById('btcStockPrice');
let lastPrice = null;
ws.onmessage = (even) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElement.innerText = price;
stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
lastPrice = price;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-3 pt-5">
<hr>
<table class="table table-bordered">
<thead class="table-success">
<tr class="text-center">
<th>BTC</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td><span id="btcStockPrice"></span></td>
</tr>
</tbody>
<thead class="table-success">
<tr class="text-center">
<th>ETH</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td><span id="ethStockPrice"></span></td>
</tr>
</tbody>
</table>
<hr>
</div>
<script src="script.js"></script>
</body>
</html>

you can do it in different ways:
use the miniticker to get all info for all crypto and filter out to show only the ones you want :
'wss://stream.binance.com:9443/ws/!miniTicker#arr'
or use a combined stream for the data you want:
'wss://stream.binance.com:9443/stream?streams=btcusdt/ethusdt'

Related

JavaScript Expense Tracker Calculator - Subtraction

Im trying to do a expense tracker with vanilla javascript that user can can add/remove their expense item and the Total of expense will be calculated accordingly.
I am using constructor to create object so later I can save in localStorage later and retrieve later (hv not done this part yet)
Here is the problem. There is no problem in adding atm but when it comes to removing item (if not remove in sequence), the calculation is messed up. E.g. Item 1, Item 2, Item 3. If I remove with order Item 3 --> Item2 --> Item No problem with total value of subtraction. But if start the removal from Item 1 or Item 2, the calculation will be messed up
Im not sure is it because there is no index/id in each item so calculation is not working. Appreciate for any help thank you!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer=document.getElementById("listContainer");
let inputField= document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
var newRow = document.createElement('tr');
var expense = document.createElement('td');
var expenseDate = document.createElement('td');
var expenseAmount = document.createElement('td');
var deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value="";
var totalAmount = parseFloat(total.innerText) || 0;
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function(){
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>
The primary issue you were experiencing is that you declared totalAmount at the local scope, so each deleteButton event listner still references the old totalAmount value from when the listener was declared. If you declare that value in a higher-level scope, alongside total, everything works as expected.
Here it is in action:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer = document.getElementById("listContainer");
let inputField = document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
let totalAmount = parseFloat(total.innerText) || 0;
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
const newRow = document.createElement('tr');
const expense = document.createElement('td');
const expenseDate = document.createElement('td');
const expenseAmount = document.createElement('td');
const deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value = "";
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function() {
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>

appendChild does not add new elements. It just replace the old elements to the new one (java script)

data variable's is 500. This variable has 500 ID of top stories of Hackers News.
and I am trying to add tr elements which shows the title of each ID and rank.
There is no problem if I only add one ID in the loop.
However, if I use more than one ID then the new tr element just replace the old tr element.
I wanted to display 500 top sorties but it only shows one story as you can see.
Is there any way to show 500 stories?
var itemlist = document.querySelector('.itemlist'); //tbody elements
var request = new XMLHttpRequest()
request.open('GET', 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', true)
request.onload = function() {
// begin accessing JSON data here
var data = JSON.parse(this.response);
for (var j = 0; j < data.length; j++) {
var temp = data[j];
var id = 'https://hacker-news.firebaseio.com/v0/item/' + temp + '.json?print=pretty';
request.open('GET', id, true)
request.onload = function() {
var data = JSON.parse(this.response);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td1 = document.createElement('td');
td.id = temp;
td.textContent = (j) + '.';
td1.textContent = data.title;
tr.appendChild(td);
tr.appendChild(td1);
itemlist.appendChild(tr);
console.log(id);
}
request.send();
}
}
request.send();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<table class="main" width="85%">
<tbody>
<tr>
<td bgcolor="#ff6600">
<table style="padding:2px;">
<tbody>
<tr>
<td style="width:18px;">
<a href="https://news.ycombinator.com/">
<img src="https://news.ycombinator.com/y18.gif" class="ylogo">
</a>
</td>
<td style="line-height:12px;height:10px">
<span class="mainmenu">
<span style="margin-right:7px;">
Hacker News
</span>
new
|
past
|
comments
|
ask
|
show
|
jobs
|
submit
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="pagespace"></tr>
<tr>
<td>
<table>
<tbody class="itemlist">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<script src="main.js"></script>
</body>
</html>

Calculating items that were entered into an array

I'm trying to find a way to calculate the data that was entered into an array.
The JavaScript
function getInput()
{
var even = [];
var odd = [];
var num = prompt("Enter your number");
if (num % 2 === 0) {
alert("Data entered into array.");
even.push(num);
}
else if (num % 2 == 1) {
alert("Data entered into array.");
odd.push(num)
}
else {
alert("Invalid input.");
}
}
function finished() //This is where the calculations are done. It's accessed by a button in my HTML.
{
var sum = document.getElementById("leftSumOutput").innerHTML = even[];
}
This is the structure for the page. I'm trying to use tables to store the outputs.
The HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample Title</title>
<script type="text/javascript" src="assignmentOne.js"></script>
<link rel="stylesheet" type="text/css" href="assignmentOne.css">
<link rel="icon" href="favicon.png" type="image/x-icon" />
</head>
<body>
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input" onclick="getInput()"><b>Click to input data</b></button><br><br>
<button id="done" onclick="finished()">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="leftSumOutput"></td>
<td id="rightSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="leftAvgOutput"></td>
<td id="rightAvgOutput"></td>
</tr>
</table>
</div>
</body>
</html>
I want to calculate the items within the array. I'm a novice, so I apologize in advance.
EDIT: I forgot to mention that I don't know how to calculate the averages of the fields either. Any help with that would be appreciated. Thanks everyone for your assistance so far!
I think you are little bit confused with scoping of variables.
Here is an example of how it could've been done:
(function(w, d) {
var odds = [], evens = [], button, elSumOdds,elSumEvens, elAvgOdds, elAvgEvens, s
w.addEventListener('load', function() {
button = d.querySelector('button')
elSumOdds = d.querySelector('#sum-odds')
elSumEvens = d.querySelector('#sum-evens')
elAvgOdds = d.querySelector('#avg-odds')
elAvgEvens = d.querySelector('#avg-evens')
button.addEventListener('click', calculate)
})
function calculate() {
var i = prompt('enter number') | 0;
if ((i|0)%2) {
odds.push(i)
s = odds.reduce(function(a,n) { return a+n }, 0)
elSumOdds.innerText = s
elAvgOdds.innerText = s / odds.length
} else {
evens.push(i)
s = evens.reduce(function(a,n) { return a+n }, 0)
elSumEvens.innerText = s
elAvgEvens.innerText = s / evens.length
}
}
})(window, document)
<button > calculate</button>
<table>
<tr><td></td><td>Sum</td><td>Avg</td></tr>
<tr><td>Odds</td><td id='sum-odds'></td><td id='avg-odds'></td></tr>
<tr><td>Evens</td><td id='sum-evens'></td><td id='avg-evens'></td></tr>
</table>
If you need to calculate sum of each element in array you need to write map function. Visit link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
if you just need to know amount of elements, call: alert(even.length);
Note: #vittore 's structure inspired this change.
(function(d) {
d.getElementById('input').addEventListener('click', getInput);
d.getElementById('done').addEventListener('click', finished);
var elSumOdd = d.getElementById('oddSumOutput');
var elSumEven = d.getElementById('evenSumOutput');
var elAvgOdd = d.getElementById('oddAvgOutput');
var elAvgEven = d.getElementById('evenAvgOutput');
var even = [];
var odd = [];
function getInput() {
var num = prompt("Enter your number") | 0;
if (num % 2 == 0) {
even.push(num);
} else if (num % 2 == 1) {
odd.push(num);
} else {
alert("Invalid input.");
}
finished();
}
function finished() { //This is where the calculations are done. It's accessed by a button in my HTML.
elSumOdd.innerHTML = odd.reduce(function(a, b) {
return a + b;
}, 0);
elSumEven.innerHTML = even.reduce(function(a, b) {
return a + b;
}, 0);
elAvgOdd.innerHTML = elSumOdd.innerHTML / odd.length || 0;
elAvgEven.innerHTML = elSumEven.innerHTML / even.length || 0;
}
})(document);
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input"><b>Click to input data</b>
</button>
<br>
<br>
<button id="done">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="evenSumOutput"></td>
<td id="oddSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="evenAvgOutput"></td>
<td id="oddAvgOutput"></td>
</tr>
</table>
</div>

deleting the table after rows are deleted

I m trying to delete the table after all the rows deleted but somehow i cant check if table has children after deleting all the rows.
I dont understand why looking for the child elements length doesnt work here ? any suggestions ?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>table manipulation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<script src="..//jquery-2.1.3.min.js"></script>
<script src="table.js" type="text/javascript"></script>
</head>
<body>
<table id = "table1">
<tr id = "1">
<td id = "information1"> i m the first row !</td>
<td><button id = "button1" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "2">
<td id = "information2"> i m the second row !</td>
<td><button id = "button2" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "3">
<td id = "information3" > i m the third row !</td>
<td><button id = "button3" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
<tr id = "4">
<td id = "information4" > i m the fourth row !</td>
<td><button id = "button4" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
</table>
<div id = "newtable"> </div>
</body>
</html>
var id ;
var table = $('<table></table>').addClass('foo');
function destroy(){
var theParent = document.querySelector("#table1");
var parent = $("#" + id).parent();
$("#" + id).fadeOut( "slow", function() {
$(parent).closest('tr').remove();
alert(theParent.innerHTML);
});
var row = $('<tr</tr>').addClass('bar').text(parent.siblings().html());
table.append(row);
$("#newtable").append(table);
parent.siblings().remove();
theParent.addEventListener("click", doSomething, false);
}
function doSomething(e) {
if($("#table1").children().length < 1 ){
theParent.remove();
}
}
function reply_click(clicked_id)
{
id = clicked_id;
destroy();
}
function doSomething(e) {
if($("#table1 tr").length <= 1 ){
theParent.remove();
}
}
This will help you
You can try this instead:
if($("#table1").find('tr').length < 1 ){
theParent.remove();
}
Browsers will usually add <tbody> and<thead> tags into a table even if they aren't in your HTML, so the rows aren't the only children. The code above just looks for rows.

How to switch between players in a Javascript tic tac toe game

I'm still a newbie in JS, would appreciate the help and any sort of explanations. So here I go; I don't have the slightest clue why my following code is not switching between "X"s and "O"s each time one of the two players clicks on whatever case they want. One thing is for sure something is wrong with the logic of my if statements.
My html is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<script text="javascript" src="tic.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<center>
<body>
<h1 style="font-family:arial;">Tic-Tac-Toe</h1>
<table>
<tr>
<td id = "case1" onclick="display_input('case1')"></td>
<td id = "case2" onclick="display_input('case2')"></td>
<td id = "case3" onclick="display_input('case3')"></td>
</tr>
<tr>
<td id = "case4" onclick="display_input('case4')"></td>
<td id = "case5" onclick="display_input('case5')"></td>
<td id = "case6" onclick="display_input('case6')"></td>
</tr>
<tr>
<td id = "case7" onclick="display_input('case7')"></td>
<td id = "case8" onclick="display_input('case8')"></td>
<td id = "case9" onclick="display_input('case9')"></td>
</tr>
</table>
<footer>
<p>Copyright© 2014</p>
</footer>
</body>
</center>
</html>
Javascript:
function display_input(square){
var player_one = 1;
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}
On every call of display_input, you intialise a new player_one variable with the same value: 1. Move the declaration outside of the function, so that subsequent calls will actually toggle the (one) higher-scoped variable:
var player_one = 1;
function display_input(square){
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}

Categories