anmarti
anmarti

Reputation: 5143

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.

Upvotes: 5

Views: 2329

Answers (6)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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" />

Upvotes: 4

Mahmoud Farahat
Mahmoud Farahat

Reputation: 5475

try this code

    $('body *').keypress(function (e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

the above code will prevent pressing enter for every element in page ,You can change the selector $('body *') to something else depending to your case

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

An other possible way i think:

$('.elems').on('click',function(){$(this).blur()});

Upvotes: 0

Paul S.
Paul S.

Reputation: 66304

Listen for "keypress" and .preventDefault()

ex. with <myelm class="nokey"/>

function noKeyPressing(){
    var elms = document.getElementsByClassName('nokey'),
        stop = function stop(e){ return e.preventDefault(), false; },
        i = elms.length;
    while(--i >= 0){
        elms[i].addEventListener('keypress', stop, true);
    }
}
noKeyPressing()

If you just want to prevent Enter then the keyCode to look for is 13.

Upvotes: 1

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

You can return false to prevent the default action.

  <input type="submit" onkeypress="return false;" value="Submit" />

Upvotes: 0

ddev
ddev

Reputation: 389

try

.unbind('keydown');

to disable all key events on your element

Upvotes: 0

Related Questions