Jquery: Different click and enter handlers

48 views Asked by At

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/

2

There are 2 answers

2
Zakaria Acharki On BEST ANSWER

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>

1
Roy Bogado On

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