Increase transfer speed by pressing mouse (hold)?

Asked

Viewed 41 times

0

I’m trying to use the buttons to transfer from one user to the other, but I would like to click and press the mouse increase the speed, already when just click, pass the values from one to one.

Can anyone help me?. I’ve already started making some attempts with addSpeed(), in JS, but still unsuccessful.

The code below is only to be able to reproduce here, the complete code with css did not fit in the Snippet, if you want to view follows Jsfiddle.

//var minValue = 10; //10MB


function formatNumberComma (num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

function formatNumber(num){
   num = num/1000;

  if(num == parseInt(num)){
    return formatNumberComma(parseInt(num));
  }

  return formatNumberComma(num.toFixed(2));
}

//server side values
var initialValuesUserbar = {
  'minValue': 10, //min value
  'usersInfo': [
    //left
    {
      name: 'Marianna',
      value: 50000,
      avulso: 4000,
      bloqueado: true
    },
    //right
    {
      name: 'Ludmilla',
      value: 50000,  //3000
      avulso: 0,
      bloqueado: false
    }
  ]
}

var currentValuesUserbar = [];


var setInitialBarValues = function(values){
  //console.log(values)
  var usersInfo = values.usersInfo;
  var left = usersInfo[0];
  var right = usersInfo[1];

  currentValuesUserbar.push(left.value)//[0]
  currentValuesUserbar.push(right.value)//[1]

  //$('.warn-message-info.ator-desabilitado').hide();
  $('.blocknumber-left').hide();
  $('.blocknumber-right').hide();

  if(left.bloqueado) $('.blocknumber-left').show();
  if(right.bloqueado) $('.blocknumber-right').show();

  //left
  $('.left-name').text(left.name)
  $('.left-value').text(formatNumber(left.value));

  // if(left.avulso) {
  //   $('.left-avulso-value').text("+" + formatNumber(left.avulso) +" GB avulso")
  // }

  $('.right-name').text(right.name)
  $('.right-value').text(formatNumber(right.value))

  // if(right.avulso){
  //   $('.right-avulso-value').text("+" + formatNumber(right.avulso) +" GB avulso")
  // }
}

function addSpeed(){
  hold_trigger.mousedown(function() {
          
    userEventClickId = setTimeout(funcao_teste, hold_time);
  }).bind('mouseup mouseleave', function() {
      clearTimeout(userEventClickId);
      // voltar ao tempo normal aqui
  });

  function funcao_teste() {
    // acelerar o tempo aqui
  }
};

function clearErrorAdd(){
  $('.left-container-avulso').removeClass('nactive')
  $('.right-container-avulso').removeClass('nactive')
  $('.warn-message-info.ator-desabilitado').removeClass('active');
  $('.warn-message-info.ator-desabilitado').addClass('nactive');
  $('.panel-heading__blockNumber').removeClass('dipnone');

}

function showWarningMessage(className){
  $(className).addClass('nactive')
  $('.warn-message-info.ator-desabilitado').removeClass('nactive');
  $('.warn-message-info.ator-desabilitado').addClass('active');
  $('.warn-message-info.ator-desabilitado .phone').text(initialValuesUserbar.usersInfo[0].phone);
  $('.panel-heading__blockNumber').addClass('dipnone');
}

function incrementRight(hasAnimation){
  
  if(currentValuesUserbar[0] > initialValuesUserbar.minValue){
    currentValuesUserbar[0] -= 10;
    currentValuesUserbar[1] += 10;
    $('.left-value').text(formatNumber(currentValuesUserbar[0]))
    $('.right-value').text(formatNumber(currentValuesUserbar[1]))

    clearErrorAdd();

    $('.right-container-avulso').addClass('animate')

    if(hasAnimation){
      setTimeout(function(){
        $('.right-container-avulso').removeClass('animate')
      }, 300)
    }
  } else {
    $('.right-container-avulso').removeClass('animate')
    showWarningMessage('.left-container-avulso')
    return true;
  }
  
}


function incrementLeft(hasAnimation){
  
  if(currentValuesUserbar[1] > initialValuesUserbar.minValue){
    currentValuesUserbar[1] -= 10;
    currentValuesUserbar[0] += 10;
    $('.left-value').text(formatNumber(currentValuesUserbar[0]))
    $('.right-value').text(formatNumber(currentValuesUserbar[1]))

    clearErrorAdd();

    $('.left-container-avulso').addClass('animate')

    if(hasAnimation){
      setTimeout(function(){
        $('.left-container-avulso').removeClass('animate')
      }, 300)
    }
  } else {
    $('.left-container-avulso').removeClass('animate')
    showWarningMessage('.right-container-avulso')
    return true;
  }
}

//document ready
window.onload = function(){


function menu_toggle() {
  $('.spinner').addClass('active');
}
  
  var userEventClickId = 0;
  var incrementTimeInterval = 200;

  var hold_time = 1000; // tempo para começar a acelerar
  hold_trigger = $('.btn-left'); 

  var time = 150;

  $('.btn-right').click(function(event){
    event.preventDefault();

    incrementRight(true);
  })
  .on('mousedown', function(event) {
      event.stopPropagation();
      event.preventDefault();
    
        userEventClickId = setInterval(function(){
          if(incrementRight()) {
            clearInterval(userEventClickId);
            return;
          }
        }, time); //150
  }).on('mouseleave', function(event) {
      event.stopPropagation();
      event.preventDefault();

      clearInterval(userEventClickId);
      $('.right-container-avulso').removeClass('animate')
  });

  $('.btn-left').click(function(event){
    event.preventDefault();
    incrementLeft(true);
  })
  .on('mousedown', function(event) {  
      event.preventDefault();
      userEventClickId = setInterval(function(){
        if(incrementLeft()) {
          clearInterval(userEventClickId);
          return;
        }
      }, time); //150
  })
  .on('mouseleave', function(event) {
      event.stopPropagation();
      event.preventDefault();

      clearInterval(userEventClickId);

      $('.left-container-avulso').removeClass('animate')
  });
  //set initial
  setInitialBarValues(initialValuesUserbar);
}
<!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 href="main.css" rel="stylesheet">
    <script src="./transferencia.js"></script>
    <script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>
</head>
<body>
  <div id="home-produto" class="main pull-left">



              <!-- style_minhaoi_nav_produto :: INICIO -->
            <div id="divContent">
              <!-- begin: style_minhaoi_container_plano -->
              <div id="box-internet">
                      <div class="panel panel-default row box-produto">
                          <div class="panel-body">



                      <section class="section__title">
                        <p class="title-cingapura">Transferência de valores</p>
                      </section>




                                  <section class="section__transferencia--selecionados">
                        <div class="panel panel-default text-align--center col-xs-5 left-container-avulso">
                         <div class="panel-heading">
                            <p class="panel-heading__itemName left-name"></p>
                            <span class="panel-heading__itemNumber cor__second left-phone"></span>
                         </div>
                         <div class="panel-body">
                            <p class="panel-heading__itemQty">
                              <span class="left-value"></span>
                              <span class="panel-heading__itemQty--lower"> GB</span>
                            </p>

                         </div>
                       </div>
                       <ul class="transferencia-arrows col-xs-1">
                         <li><a href="#" class="btn-right">
                         <button class="material-icons arrow-icon">
                         >
                         </button>
                         </a></li>
                         <li><a href="#" class="btn-left"><button class="material-icons arrow-icon"><</button></a></li>
                       </ul>
                        <div class="panel panel-default text-align--center col-xs-5 right-container-avulso">
                         <div class="panel-heading">
                            <p class="panel-heading__itemName right-name"></p>
                            <span class="panel-heading__itemNumber cor__second right-phone"></span>
                         </div>

                         <div class="panel-body">
                             <p class="panel-heading__itemQty">
                               <span class="right-value"></span>
                               <span class="panel-heading__itemQty--lower"> GB</span>
                             </p>

                          </div>
                         </div>
                       </div>

                                  </section>



                                  </div>
                              </div>

                              <!-- end: div_box_produto -->
                  </div>
                  <!-- end: div_id_produto -->
                  <!-- end: style_minhaoi_container_plano -->

                  </div>
                  <!-- end: div_content -->
          </div>
</body>
</html>

1 answer

0

take a look at this example, maybe it will enlighten you on how you can make this functionality.

const TICK = 300; // milliseconds

var initialSpeed = 1;
var maxSpeed = 100;

var initialStorage = 200;

var speedValue = document.createTextNode(initialSpeed);

var currentStorageValue = document.createTextNode(initialStorage);
var currentBackpackValue = document.createTextNode(0);

document.querySelector('#speed').appendChild(speedValue);
document.querySelector('#storage').appendChild(currentStorageValue);
document.querySelector('#backpack').appendChild(currentBackpackValue);

/*
  Transfere do storage p/ backpack.
  Utiliza um Timeout para chamar a função novamente após
  o tempo estipulado. (Evita o problema que ocorre com o Interval
  que faz com que a animação pare quando o tempo muda)
*/
function transferToBackpack() {
  if (currentStorageValue.data <= 0) {
    console.log("Storage is empty..");
  } else {
    currentStorageValue.data--;
    currentBackpackValue.data++;
    setTimeout(transferToBackpack, (TICK / (speedValue.data / 5)));
  }
}

// Interval q executa enquanto user pressiona o mouse
var speedUpInterval;

// Interval q executa após user liberar o mouse
var speedDownInterval;
var container = document.querySelector('#press');
container.addEventListener('mousedown', function() {
  console.log('pressing...');
  if(speedDownInterval) clearInterval(speedDownInterval);
  speedUpInterval = setInterval(function() {
  	if(speedValue.data < maxSpeed) {
    	speedValue.data++;
    } else {
      clearInterval(speedUpInterval);
    }
  }, TICK);
});

container.addEventListener('mouseup', function() {
  console.log('releasing...');
  if(speedUpInterval) clearInterval(speedUpInterval);
  speedDownInterval = setInterval(function() {
  	if(speedValue.data > 1) {
    	speedValue.data--;
    } else {
      clearInterval(speedDownInterval)
    }
  }, TICK);
});

transferToBackpack();
#press {
  width: 100px;
  height: 100px;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content:center;
}
  <p>Transfer Speed: <span id="speed"></span></p>
  <p>Storage: <span id="storage"></span></p>
  <p>Backpack: <span id="backpack"></span></p>
  
  <div id="press">
    <span>Press me!</span>
  </div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.