Detect Shift key is pressed

Asked

Viewed 685 times

3

I need the javascript detects if the key shift is being kept pressed, while it is running the function, when the user drops, stops executing the function.

I’m trying to use this code on Jquery

 <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
          }
      });
  });

2 answers

1

Try using something like this code. In case you will have to adapt your code to be applied on 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 believe it will help you a little.

  • 1

    I think this will work for me, while pressing the function function works, otherwise.

1


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

Without a 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>
Pressione shift

With a Interval

// 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 but fast. Besides of course, you can adjust the delay.

Attention should be paid to the use of the event keydown, instead of keyup, since the repetition can only occur in this event.

  • Very cool idea! Thanks.

  • loved it, thank you

Browser other questions tagged

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