I am creating a tip calculator. I have a button on the page that calculates the tip if you press it or if you press enter on the keyboard. When I press the enter key, the function that calculates the tip runs but then it runs again even though I did not call it again anywhere in my code. The odd thing is, is that the second time it runs, it goes into the variable where the function is stored and runs the function. I don't know why it goes into a variable that wasn't called.

I tried debugging to see if I missed a step and if I called the function twice somewhere, but I didn't.

Here is the keypress event:

document.addEventListener('keypress', function(event) {
      if (event.keycode === 13 || event.which === 13) {
        calculateTip();
      }

Then right after that code is the calculateTip variable:

var calculateTip = function() {
   some code that does calculations
}

After the key is pressed, calculateTip is executed, then it goes straight into the above variable to run calculateTip again.

I have my code inside an IIFE. I already tested to see if the code outside of this IIFE affected anything, it doesn't. The 'click' event listener works perfectly and only executes the calculateTip function once. In this version of my code, calculateTip will print 'test' to the console twice if enter is clicked.

The IIFE:

var controller = (function(calcCtrl, UICtrl) {

  var setupEventListeners = function() {

    var DOM = UICtrl.getDOMstrings();

    document.querySelector(DOM.button).addEventListener('click', calculateTip);

    document.addEventListener('keypress', function(event) {
      if (event.keycode === 13 || event.which === 13) {
        calculateTip();
      }
    });
  };

var calculateTip = function() {
 console.log('test')
};

return {
    init: function() {
      setupEventListeners();
    }
  }

})(calculateController, UIController);

controller.init();

3 Answers

0
Onur Gelmez On Best Solutions

with jquery you can solve it

$(document).unbind('keypress').bind('keypress', function (e) {
    if (e.keycode === 13 || e.which === 13) {
    calculateTip();
  }
});
0
Obaidul Kader On

It's give one time would you please check this out.

<script type="text/javascript">
    document.addEventListener('keypress', function(event) {
          if (event.keycode === 13 || event.which === 13) {
            calculateTip();
          }
     });
    var calculateTip = function() {
       console.log("enter clicked");
    }
</script>
0
Daniel Kemeny On

Try to put the following to your event listener function:

event.stopImmediatePropagation();