Sliders Co
Sliders Co

Reputation: 3

Disable enter key to click a button

how can you disable to enter key to click a button. So when a button is focused, and the enter key pressed you wont click the button.


I made a Aim Trainer code, but there is a cheat: you can press the enter button to click instead of clicking with your mouse (or finger on mobile).

You can see what I mean here https://aimtrainer.netlify.com/clickbased.html

If you click the enter button there should happen nothing, but now you will trigger some sort of click event.

I tried this: but that wouldnt work

$('html').bind('keypress', function(e){
  if(e.keyCode == 13)
  {
    return false;
  }
});

Upvotes: 0

Views: 3207

Answers (3)

mplungjan
mplungjan

Reputation: 177684

You need preventDefault() and blur

Other good ideas: tabindex="-1" type="button"

let score = 0;
const addScore = function(val) {
  score += val;
  $("#score").html('score: ' + score);
}

const newRandomPosition = function() {
  $("#button").css({
    'left': ranNum(90) + 'vw',
    'top': ranNum(90) + 'vh',
    'opacity': 1
  })
}

const ranNum = function(max) {
  return Math.random() * max
}

$(function() {
  $(document).on('keypress', function(e) {
    if (e.target && e.target.id === "button" && e.which == 13) {
      e.preventDefault()
    }
  });

  $("#button")
    .on("click", function(e) {
      e.preventDefault();
      //	openFullscreen()
      $(this).css("opacity", 0)
      addScore(100)
      newRandomPosition()
    })
    .on("focus", function() {
      this.blur()
    })

});
.button {
  position: relative;
  background-color: #FB6107;
  border: none;
  color: white;
  padding: 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button tabindex="-1" type="button" id="button" class="button button5"></button>
<h1 id="score" class="scoreText">Score: 0</h1>

Upvotes: 0

User863
User863

Reputation: 20039

Set tabindex as -1 to avoid focus using tab key

<button id="button" class="button button5" onclick="hidebtn(this)" tabindex="-1"></button>

Manually focusout the button using blur()

function newRandomPostion(){
    $("#button").css({left:ranNum(90)+'vw',top:ranNum(90)+'vh'});
    $("#button").css('opacity', 1);
    $("#button").blur();
}

Upvotes: 0

Leon Vuković
Leon Vuković

Reputation: 489

Did you tried with e.preventDefault()?

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        e.preventDefault()
    }
});

Upvotes: 1

Related Questions