Search code examples
javascriptjqueryhtml

Prevent Enter key works as mouse click


I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.

In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.

enter image description here

Is there any way to make it global way? Thank you.


Solution

  • To address this you can call preventDefault() on the event that's raised. You can detect the key that was pressed, and if it was the Return key, cancel its default behaviour. Try this:

    $(".myElements").on('keypress', e => {
      if (e.key == 'Enter') {
        e.preventDefault();
        console.log('Enter key was pressed');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input class="myElements" />