Search code examples
javascriptkeypress

Keydown and keyup for existing function


Currently I have buttons to control a rover. One for example is called "forward" and when pressed down accelerates, but when released stops the rover again. Now I want to implement a control of the rover via keypress. So e.g. "w" should accelerate on keydown and stop on keyup. The sites i have found so far do not show how to include my already existing function in a JS for keydown and keyup. I can not code well enough to figure that out myself. They only show how to print a message when key is pressed. Can somebody help me out here?

EDIT: Code and solution can be found in the answer below

EDIT2: Solution with my edit for keys is right here

function functForward{
    var myRPM = document.getElementById('slider').value;
    var myAng = document.getElementById('slider2').value;

    //functForward code
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML = this.responseText;
        }
      };
      var request = "?drive=1" + "&rpm=" + myRPM + "&ang=" + myAng;
      console.log(request);
      xhttp.open("GET", request, true);
      xhttp.send();
}

function functStopDrive(){
    var myRPM = document.getElementById('slider').value;
    var myAng = document.getElementById('slider2').value;

    //funcstopdrive code
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML = this.responseText;
        }
      };
      var request = "?drive=0" + "&rpm=" + myRPM + "&ang=" + myAng;
      console.log(request);
      xhttp.open("GET", request, true);
      xhttp.send();
}

var addEvent = document.addEventListener ? function(target, type, action) {
  if (target) {
    target.addEventListener(type, action, false);
  }
} : function(target, type, action) {
  if (target) {
    target.attachEvent('on' + type, action, false);
  }
}

addEvent(document, 'keydown', function(e) {
  e = e || window.event;
  var key = e.which || e.keyCode;
  if (key === 87) {
    functForward();
  }
});
addEvent(document, 'keyup', function(e) {
  e = e || window.event;
  var key = e.which || e.keyCode;
  if (key === 87) {
    functStopDrive();
  }
});

<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> 
</script>
<div class="col-sm-4">
<button id="Forward" type="button" class="btn btn-success btn-lg btn-block" 
ng-mousedown="functForward();" ng-mouseup="functStopDrive();">Forward</button>
</div>

<div id="slidecontainer">
 <input type="range" ng-model="myRPM" min="0" max="8000" id="slider" step="500">

 <input type="range" ng-model="myAng" min="-60" max="60" id="slider2" step="5">
</div>

Solution

  • You could use functions onkeydown and onkeyup attached to the document Object.

    Edit 1

    I have edited the answer to break the functions out to be separate from the key listeners so that they are accessable from the button.

    Edit 2

    First, I would make the sliders have ids not just classes, as this will make it easier for you to parse.

    Instead of passing the values into the functions as you have done, I recommend asking the DOM for the values each time the function runs, as I have edited to code below to do:

    function functforward{
            var myRPM = document.getElementById('slider').value;
            var myAng = document.getElementById('slider2').value;
    
            //funcforward code
              var xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                  document.getElementById("demo").innerHTML = this.responseText;
                }
              };
              var request = "?drive=1" + "&rpm=" + myRPM + "&ang=" + myAng;
              console.log(request);
              xhttp.open("GET", request, true);
              xhttp.send();
    }
    
    function functStopDrive(){
            var myRPM = document.getElementById('slider').value;
            var myAng = document.getElementById('slider2').value;
    
            //funcstopdrive code
              var xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                  document.getElementById("demo").innerHTML = this.responseText;
                }
              };
              var request = "?drive=0" + "&rpm=" + myRPM + "&ang=" + myAng;
              console.log(request);
              xhttp.open("GET", request, true);
              xhttp.send();
    }
    
    document.onkeydown = function (e) {
        if(e.key == 81){
             functForward();
        }
    }
    
    document.onkeyup = function (e) {
        if(e.key == 81){
            functStopDrive();
        }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div class="col-sm-4">
      <button id="Forward" type="button" class="btn btn-success btn-lg btn-block" ng-mousedown="functForward();" ng-mouseup="functStopDrive();">Forward</button>
    </div>
    
    <div id="slidecontainer">
      <input type="range" ng-model="myRPM" min="0" max="8000" id="slider" 
    step="500">
    
      <input type="range" ng-model="myAng" min="-60" max="60" 
    id="slider2" step="5">
    </div>