Vivek Vivi
Vivek Vivi

Reputation: 51

Jquery / javascript error to get live result in my project

Currently I am working in a Bitcoin live price project with jquery. Now I need to develop a live price difference percentage change calculator. Calculator is working fine. But not working automatically when Bitcoin live price changing. I need to edit in input. Keyup event needed for working. I need to make it as always automatically. Please make it as automatically without keyup.. I created a Codepen page for it. https://codepen.io/toolsim/pen/Rwywjap . My codes;

<script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="btc-price" class="main01 dz-none from01 for-copy01 input bldo te-cen" value="">
<input type="text" value="25000" class="main02 percentagez to01 input bldo te-cen">
<input type="text" class="rz-result result01 input bldo te-cen">

<script type="text/javascript">
$(document).on("change keyup blur", ".main02", function() {
  var first = Number($('.from01').val());
  var second = Number($('.to01').val());
  var minus = second - first; // 2000 - 1000 = {1000 = minus}
  var divide = (minus / first); // 1000 / 1000 = 1
  var multiply = divide * 100; // 1 * 100 = 100%
  $('.result01').val(Number(multiply).toFixed(2));
});
</script>

<script type="text/javascript">
    let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
    let stockPriceInput = document.querySelector('#btc-price');
    let lastPrice = null;
    weburl.onmessage = (event) => {
      let stockObject = JSON.parse(event.data);
      let price = parseFloat(stockObject.p).toFixed(2);
      stockPriceInput.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
      stockPriceInput.value = price;  
      lastPrice = price;
    };
    </script>

Upvotes: 1

Views: 78

Answers (1)

mscdeveloper
mscdeveloper

Reputation: 2889

maybe like this:

function set_bts(_price){
      $('.main01').val(_price);
      var first = Number($('.from01').val());
      var second = Number($('.to01').val());
      var minus = second - first; // 2000 - 1000 = {1000 = minus}
      var divide = (minus / first); // 1000 / 1000 = 1
      var multiply = divide * 100; // 1 * 100 = 100%
      $('.result01').val(Number(multiply).toFixed(2));
}

    var weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
    weburl.onmessage = function(event){
      var stockObject = JSON.parse(event.data);
      var price = parseFloat(stockObject.p).toFixed(2);
      set_bts(price)
    };
<script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <input type="text" id="btc-price" class="main01 from01" value="">
    <input type="text" value="25000" class="to01">
    <input type="text" class="result01">

Upvotes: 1

Related Questions