2

Im using jQuery too. Im trying to call one method keyPressEvent on pressing enter button. Whats wrong in the code

var AplOperations = function() {
  // this function i want to call when an enter button is pressed
  this.keyPressEvent = function() {
      // my code goes here
  }
} 

var myOpr = new AplOperations();

document.onkeyup = myOpr.keyPressEvent();
Julian
  • 33,915
  • 22
  • 119
  • 174
Syed Sha
  • 151
  • 2
  • 12

3 Answers3

2

You don't need the () after myOpr.keyPressEvent, other wise the function will be executed intermediately.

Working example: (click first on the panel for the focus)

    var AplOperations = function() {
      // this function i want to call when an enter button is pressed
   
      this.keyPressEvent = function() {
          // my code goes here
          var elem = document.getElementById("test");
          elem.innerHTML += "key pressed<br>"
      }
    } 

    var myOpr = new AplOperations();

    document.onkeyup = myOpr.keyPressEvent;
<div id="test"></div>
Julian
  • 33,915
  • 22
  • 119
  • 174
1

You have to wait for the keyup and execute your things in callback. Right now it executes when the script gets execute.

   document.onkeyup = function () {
        myOpr.keyPressEvent();
   }

Updated Demo

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

This line is wrong:

document.onkeyup = myOpr.keyPressEvent();

Using brackets immediately calls the function and the result is assigned to the onkeyup handler. If you remove the brackets your function will be assigned as a handler

Kiril Aleksandrov
  • 2,601
  • 20
  • 27