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;
}
});
Did you tried with e.preventDefault()
?
$(document).on('keypress',function(e) {
if(e.which == 13) {
e.preventDefault()
}
});
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>
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.