Detect Shift key is pressed

3

I need to know if the shift key is being held down, while running the function, when the user drops,

I'm trying to use this code in javascript

 <script type="text/javascript">
  $(document).ready(function(){
      $("body").keypress(function(event)
      {
         if(event.keyCode == 16)   // se a tecla apertada for 13 (enter)
          {
            /* funçao a ser executada */
             teste(); // abre uma janela
          }
      });
  });

    
asked by anonymous 26.10.2016 / 19:22

2 answers

1

Focusing more on the part of the function execution while it is pressed:

Without an Interval

var count = 0;
var mainFunction = function(){
	console.log(++count);
}

$(document).keydown(function(e){
	e.preventDefault();
	if(e.shiftKey) mainFunction();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Pressioneshift

WithanInterval

// mainFunction será sua função executada

var count = 0;
var mainFunction = function() {
  console.log(++count);
}


var execFunction; //interval com a função

$(document).keydown(function(e) {
  e.preventDefault();
  if (e.shiftKey) {
    clearInterval(execFunction);
    execFunction = setInterval(function() {
      mainFunction();
    }, 10);
  }
})
$(document).keyup(function(e) {
  e.preventDefault();
  clearInterval(execFunction);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>O contador irá ser executado enquanto a tecla shift estiver sendo pressionada.</h2>

Depending on how fast you want your function to run, I recommend using setInterval , because if you pay attention the call is faster. Besides of course, you can adjust delay .

What you should pay attention to is the use of keydown , instead of keyup , since replication can only occur in that event.

    
26.10.2016 / 19:52
1

Try to use something like this code. In case you have to adapt your code to be applied in body .

function teste(e){
    var evt = e || window.event;
    if (evt.shiftKey) {
      shiftKeyDown = "Pressionado";
      alert(shiftKeyDown);
    } else {
      shiftKeyDown = "Não Pressionado";
      alert(shiftKeyDown);
    }
}
<button onclick="teste()">Pressione Shift (Ou não)</button>

I think it will help you a little bit.

    
26.10.2016 / 19:43