2

There is a button. I want to detect whether the user has clicked on it or he pressed enter, and do something corresponding to which event occurred. However, when I press enter, both the click and the enter handlers are ecexuted.

How can I solve this problem?

HTML:

<button type="button">
  Click me
</button>

Jquery:

$("button").keydown(function(e){
    var keyCode = e.keyCode || e.which;
  if(keyCode === 13){
      $("button").after("<div> enter was pressed </div>");
    }
})

$("button").click(function(){
    $("button").after("<div> click event </div>");
})

https://jsfiddle.net/75wbo7d2/1/

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
themis93
  • 119
  • 1
  • 9

2 Answers2

1

Working fiddle

Use keyPress instead :

$(document).keypress(function(e) {
  var keyCode = e.keyCode || e.which;
  if(keyCode === 13){
    $("button").after("<div> enter was pressed </div>");
  }
});

$("button").click(function(){
  $(this).blur().after("<div> click event </div>");
})

Hope this helps.

$(document).keypress(function(e) {
  var keyCode = e.keyCode || e.which;
  if(keyCode === 13){
    $("button").after("<div> enter was pressed </div>");
  }
});

$("button").click(function(){
  $(this).blur().after("<div> click event </div>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">
  Click me
</button>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Thank you for your response! This works fine, except the first time that someone presses enter. – themis93 Jan 10 '17 at 12:22
  • You're welcome, glad i could helps, for the first time you've just to focus on the document because the event attached to `document`, so just click anywhere inside page then click enter. – Zakaria Acharki Jan 10 '17 at 12:34
1

Look https://jsfiddle.net/75wbo7d2/3/ with a e.preventDefault(); you can do it. Cheers

Roy Bogado
  • 4,299
  • 1
  • 15
  • 31
  • Thank you for your response. I read somewhere that using preventDefault() is not a very good option because I may cause problems. Is that right? – themis93 Jan 10 '17 at 12:24