rmoestl
rmoestl

Reputation: 3155

How to detect if click event has been triggered by 'Enter'?

//...
<a href="#" id="foo-link">Foo</a>
<script type="text/javascript">

  $('#foo-link').click(function(e) {
    //...
  }

</script>
//...

Using jQuery on a HTML page, the above defined click handler is executed

  1. when the user clicks it and
  2. when the user navigates to it via Tab and hits Enter

(At least in Firefox) there seems to be no difference between the click events passed to the handler - the original key event 'magically' translates to a click event.

Is there a way to differentiate between those two cases?

To give more details on why I need to treat those two cases differently: in my particular case the click handler sets the focus to a text input field. This text input field has a keyup event handler registered which sends an AJAX request. When the click handler was triggered after the user hitting Enter on the link, the keyup event is received by the now focused text input field and the AJAX request is sent mistakenly.

Upvotes: 16

Views: 12368

Answers (8)

slightlyfaulty
slightlyfaulty

Reputation: 1411

You could just check for the presence of mouse coordinates:

function handleClick(event) {
  if (!event.originalEvent.clientX && !event.originalEvent.clientY) {
    // Enter key pressed
  }
}

The only time this wouldn't work is when the top-left most pixel of the page is being clicked. In most cases this shouldn't be an issue.

Upvotes: 0

b00t
b00t

Reputation: 419

If the event detail is === 0, it was fired by keyboard.

$('#foo-link').click(function(e) {
  // e.detail should be enough in the latest version of jQuery.
  if (e.originalEvent.detail) {
    $(this).val('Fired by mouse.');
  } else {
    $(this).val('Fired by keyboard.');
  }
});
#foo-link {
  width: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo-link" type="button" value="Press me." />

Upvotes: 3

TJ Markham
TJ Markham

Reputation: 211

Is there a way to differentiate between those two cases?

Yes, there is (at least in Chrome):

$('#foo-link').click(function(event) {
    if (event.originalEvent.detail === 0) {
        // keyboard "click" event
    } else {
        // mouse "click" event
    }
}

You can check the detail property of the original event to get the click count. If the click count is 0, you know that the "click" came from the keyboard. If the click count is greater than 0, you know that the "click" came from the mouse.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

Upvotes: 16

Rakesh Juyal
Rakesh Juyal

Reputation: 36769

Probably a bit long method to handle this, but that worked : http://jsbin.com/azATuHe/3 ( Check console.log )

 $('.txtB').on('keyup', function(e){ 
    if ( $('#anSetF').data('enterpressed' ) == true ) {
      console.log ( 'keyup triggered on TEXTBOX but suppressed' );
      $('#anSetF').data('enterpressed', false )
      return true;
  }else{
    console.log ( 'keyup triggered on TEXTBOX Fire AJAX now : ' +  $('#anSetF').data('enterpressed' ) );
    //Existing code to fire AJAX
  }


  });

$('#anSetF').on('keydown.Enter', function(e){
    console.log('KEY UP: ' + e.which );
    if ( e.which == 13 ){
       $(this).data('enterpressed',true);
    }
  }).on('click', function(){
      //Some code which you used to focus the textbox
      $('.txtB').focus();
  });

Upvotes: 1

Igerko
Igerko

Reputation: 79

This should work

$('#foo-link').keyup(function(e) {
        if(e.which == 13)
            console.log('Enter is pressed');
});

Upvotes: -1

Mirage
Mirage

Reputation: 1487

Make the outline:0 for your link. Now, the user can't tab see the outline on the link. So, he wouldn't know which button he on, so he won't tap enter key but focus will be there on the element and if he presses enter, do your thing else do your thing. Even if won't set the outline:0 still the code works because focus is on it.

Upvotes: -2

iTURTEV
iTURTEV

Reputation: 331

One solution is to handle 'mouseup' instead of click:

<a href="javascript:;" id="foo-link">Foo</a>
<script type="text/javascript">

      $('#foo-link').mouseup(function (e) {
              alert("Mouse click");
      });

</script>

The other solution is to handle both 'click' and 'keypress' and to return false if 'enter' is pressed:

<a href="javascript:;" id="foo-link">Foo</a>
<script type="text/javascript">

    $('#foo-link').click(function (e) {
        alert("Mouse click");
    });

    $('#foo-link').keypress(function (e) {
        if (e.which == 13)
            return false;
    });

</script>

Upvotes: 3

Moelbeck
Moelbeck

Reputation: 640

I had something similar with my script. But I ended up with using .keyup instead of the click. It allowed me to check which button was clicked.

        $("#searching").keyup(function () {
        if (window.event.keyCode == 38 || window.event.keyCode == 40 || window.event.keyCode == 32) {
            return false;
        }
        var mystring = document.getElementById('searching').value;
        if (timeoutReference) clearTimeout(timeoutReference);
        if (!mystring.match(/\S/)) {

            $.ajax({
                    //Rest of code here..

Upvotes: -1

Related Questions