1

I am creating an "mousedown" event on an element and toggling a variable if shift key is pressed down. I also want to make the variable false when the "mouseup" event occurs.

element.addEventListener("mousedown", (e)=>{
            if(e.shiftKey){
                this.start = true;
            } else {
                this.start = false;
            }
        });

I want to make the this.start to false when the mouseup occurs subsequently after the above code. Could anyone help me out with it.

Thank you.

zelda
  • 753
  • 2
  • 8
  • 19

3 Answers3

2

Firstly listen for key presses on Shift

var shiftIsPressedDown = false;
$(window).keydown(function(evt) {
  if (evt.which == 16) { // shift
    shiftIsPressedDown = true;
  }
}).keyup(function(evt) {
  if (evt.which == 16) { // shift
    shiftIsPressedDown = false;
  }
});

Then look into the mouse down event

$( "#target" ).mousedown(function() {
   if(shiftIsPressedDown){
     // Do logic here     
   }
});
Joshua Duxbury
  • 4,892
  • 4
  • 32
  • 51
1

Take a look at https://api.jquery.com/mouseup/ it talks about the

.mouseup()

function which is what you are looking for i believe. It is essentially shorthand for the following syntax:

.on('mouseup', handler)

which can be used like so:

$( "#target" ).mouseup(function() {
  alert( "Handler for .mouseup() called." );
});

The full example from the documentation is as follows:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>mouseup demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Press mouse and release here.</p>

<script>
$( "p" )
  .mouseup(function() {
    $( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
  })
  .mousedown(function() {
    $( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
  });
</script>

</body>
</html>
axwr
  • 2,118
  • 1
  • 16
  • 29
-1

What I believe is working code for this question, adapted from: jQuery keyboard event handler press and hold

var keysdown = {};
// keydown handler
$(document).keydown(function(e){
  // Do we already know it's down?
  if (keysdown[e.keyCode]) {
      // Ignore it
      return;
  }
  // Remember it's down
  keysdown[e.keyCode] = true;

  // Do our thing
  if (e.keyCode == 16){
      $(document).mousedown(function(){
         //this.start = true;                   
         console.log("this.start=true")
      });
      $(document).mouseup(function(){
         //this.start = false;
         console.log("this.start=false")
      });
  }
});
// keyup handler
$(document).keyup(function(e){
  // Remove this key from the map
  delete keysdown[e.keyCode];
});
Community
  • 1
  • 1
Dshiz
  • 3,099
  • 3
  • 26
  • 53