Disable enter key to click a button - javascript

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();
}

Related

how to change class on button click in javascript

I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other
Code
var form = document.querySelector("form");
form.addEventListener("click", function(event) {
event.preventDefault();
const classId = event.target.id;
if (classId == "go") {
event.target.className = "go";
} else if (classId == "stop") {
event.target.className = "stop";
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>
You're adding the class to the clicked button, but never removing the class from the other button.
var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");
form.addEventListener("click", function(event) {
event.preventDefault();
if (event.target == goButton) {
goButton.classList.add("go");
stopButton.classList.remove("stop");
} else if (event.target == stopButton) {
stopButton.classList.add("stop");
goButton.classList.remove("go");
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>

Stop keyboard event bubbling to parent

We have a pill which contains label and a button. After selecting the pill, we can remove it on Delete or Backspace key. Also the same can be deleted on button click within the pill.
Question: When I focus on the button within the pill and press either Delete or Backspace then the event on the parent is been triggered(onKeyPress function is been called). The issue I am facing is how to stop these keyboard events (Delete & Backspace) from been called when we are on button.
Tried, preventDefault and stopPropagation. Nothing seems to be working.
<span class="pill" tabindex="0">
<span>Pill<span>
<button type="button" class="btn">X</button>
</span>
function onKeyPress(e) {
switch (e.keyCode) {
case 46:
case 8:
e.preventDefault();
handleClose();
break;
default:
break;
}
}
function handleClose() {
console.log('Clear the pill!');
}
document.querySelector('.pill')
.addEventListener('keydown', onKeyPress);
document.querySelector('.btn')
.addEventListener('click', handleClose);
You can use stopPropagation like this. The event is bubbling up from button to its parent the span. You can check for key codes and stop propagation accordingly.
//Check for your specific keycodes here:
function clickButton(e){
if(e.keyCode == 46 || e.keyCode == 8)
e.stopPropagation();
}
document.querySelector('.btn')
.addEventListener('keydown', clickButton);
You can remove the check but that will not trigger even the Enter and Tab key.
Add tabindex="-1" to the nested <button> element (you will likely want this, anyway), then handle/override focus that results from clicks. If I were building this, I would prefer focus be placed on the overall pill if I clicked anywhere on/within it, so that's what I'm demonstrating in the snippet below:
function onKeyPress(e) {
switch (e.keyCode) {
case 46:
case 8:
console.log(`${e.target.className} is in focus`);
handleClose(e);
break;
default: break;
}
}
function handleClose(e) {
console.log('Clear the pill!');
}
// Re-places focus after processing clicks on nested elements
const pillElement = document.querySelector('.pill');
pillElement.addEventListener('click', () => { pillElement.focus(); });
pillElement
.addEventListener('keydown', onKeyPress);
document.querySelector('.btn')
.addEventListener('click', handleClose);
.pill {
border: .25em solid black;
padding: .25em;
border-radius: 1em;
background-color: black;
color: white;
font-family: sans-serif;
}
.pill:focus,
.pill:active {
border-color: blue;
outline: none;
}
.pill > .btn {
border: 0;
background-color: transparent;
color: inherit;
font-family: inherit;
cursor: pointer;
border-radius: 50%;
line-height: 1.5em;
vertical-align: middle;
}
.pill > .btn:hover {
background-color: #333;
}
<span class="pill" tabindex="0">
<span>Pill</span>
<button type="button" class="btn" tabindex="-1">✕</button>
</span>

How to avoid first Character value is “-“from the Word entered in the Input box

I need to avoid only first character value is - symbol in text box.
$(document).on("keypress", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
return true
} else {
return false
}
});
I am trying this method it is not working properly.
Kindly guide me to resolve the issue.
You need to swap what you have given:
$(document).on("keyup", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
$('#form_name').val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="form_name" />
I have also added a small error message with this. Check it out:
$(".error").hide();
$(document).on("keyup", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
$('#form_name').val("");
$(this).next(".error").fadeIn();
return false;
} else
$(this).next(".error").fadeOut();
});
.error {display: inline-block; vertical-align: middle; padding: 2px; border: 1px solid #f00; background: #f66; color: #fff; font-weight: bold; font-size: 0.8em; border-radius: 3px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="form_name" />
<span class="error">Cannot start with -.</span>
$(document).on("keyup", "#form_name", function() { //when a user types in input box
var formValue = this.value;
if ( formValue.charAt( 0 ) == '-' ) {
return false;
} else {
return true;
}
});

Context menu event not working on ie when spellcheck is on

While attaching a contextmenu event to a content-editable div filled with spelling mistakes, IE(11) is ignoring the callback and showing its own Spell-check menu.
jsbin: http://jsbin.com/favit/3/ (You should preview it, then edit the div, and you will see the problem)
Turning off Spell-check is not an option, because i can't tell clients to do so.
I came across this question on Google and I figured I would post an answer in case anyone else Googles this. This is how to add your own context menu on IE without disabling spellcheck. It even works when you right-click on an incorrectly-spelled word with a red underline beneath it.
Basically, there are 2 steps:
1) In the mousedown event, you need to disable spellcheck on the contenteditable element.
2) Afterwards, you re-enable spellcheck on the contenteditable element.
Below is a working example.
var editable = $('#editable');
var mouseX, mouseY;
$(document).mousemove(function(event) {
mouseX = event.pageX;
mouseY = event.pageY;
});
editable.mousedown(function(e) {
if (e.button == 2) {
editable.attr('spellcheck','false');
e.preventDefault ? e.preventDefault : e.returnValue = false;
e.stopPropagation();
return false;
}
return true;
});
editable.get(0).oncontextmenu = function(e) {
e.preventDefault ? e.preventDefault : e.returnValue = false;
return false;
};
editable.on("contextmenu", function(e) {
e.preventDefault ? e.preventDefault : e.returnValue = false;
e.stopPropagation();
if ($('#contextmenu').length == 0) {
$('<div>').attr('id', 'contextmenu').appendTo('body');
$('#contextmenu').css('z-index', 1000);
$('#contextmenu').css('position', 'absolute');
$('<ul>').appendTo('#contextmenu');
$('<li>').html('some').appendTo('#contextmenu ul');
$('<li>').html('text').appendTo('#contextmenu ul');
$('<li>').html('here').appendTo('#contextmenu ul');
}
$('#contextmenu').css('top', mouseY);
$('#contextmenu').css('left', mouseX);
$('#contextmenu li').click(function() {
$('#contextmenu').remove();
editable.attr('spellcheck','true');
});
});
#contextmenu {
border: 1px solid #000;
background-color: #fff;
padding: 5px;
}
#contextmenu ul {
list-style-type: none;
padding: 0px;
margin: 0px;
}
#contextmenu li {
cursor: pointer;
padding: 2px;
}
#contextmenu li:hover {
background-color: #2daade;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable" contenteditable="true">Click me and type some badly spelled words.</div>
Got it:
Adding the attribute "spellcheck", setting its value to "false" has fixed it.
<div contenteditable="true" spellcheck="false">
example notaword
</div>

Make it so 'Go/Enter' key is pressable

I have a basic form which makes it so the user cannot leave the input field empty before the form posts the page. It also prevents the user from entering gibberish and requires them to only enter numbers, but this also blocks all keys that aren't numbers including the Go/Enter on mobile keyboards. My question is, is there a way to make it so that the user has to enter only numbers, but also be able to press Go after they have entered the field?
FIDDLE:http://jsfiddle.net/schermerb/nX8Hx/
Currently a user has to input a zip THEN tap back on the screen and THEN click submit.
$(document).ready(function () {
$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Enter Valid Zip!").show().fadeOut("5000");
return false;
}
});
});
var initVal = "Have a good name for it? Enter Here";
$(document).ready(function () {
$(".submit-name").attr("disabled", "true");
$(".recipe-name").blur(function () {
if ($(this).val() != initVal && $(this).val() != "") {
$(".submit-name").removeAttr("disabled");
} else {
$(".submit-name").attr("disabled", "true");
}
});
});
input {
width: 100%;
background: #FFFFFF;
border-radius: 4px;
border: 2px solid #acd50b;
padding: 10px 15px;
text-align: center;
-webkit-appearance: none;
color: #999999;
font-size: 11px;
}
input[type="focus"] {
outline: none;
}
input[type="submit"] {
border-radius: 4px;
border: 2px solid #2d8b1b;
-webkit-appearance: none;
background: #acd50b;
padding: 6px 10px;
color: #444444;
width: 100%;
font-size: 18px;
cursor:pointer;
}
.box {
width: 85px;
}
.boxtwo {
width: 160px;
}
<form action="google.html" method="get" id="recipename">
<div class="box">
<input onFocus="this.value=''" type="text" value="Enter Your Zip" placeholder="Enter Your Zip" /><span id="errmsg"></span>
</div>
<div class="boxtwo">
<input type="submit" value="Compare" id="register" disabled value="Compare" class="submit-name" />
</div>
</form>
It would be better to use keydown and test the resulting value and revert it rather than only allowing certain characters to be inserted.
$("#quantity").keydown(function (e) {
var self = this;
var tempVal = this.value;
setTimeout(function () {
if (!isValidZip(self.value)) {
self.value = tempVal;
}
}, 0);
});
function isValidZip(zip) {
return /^[0-9]{1,5}$/.test(zip);
}
http://jsfiddle.net/nX8Hx/3/
This could also be done with keyup or keypress, however keydown makes it happen much quicker and allows you to easily get the previous value.
Doing it this way avoids the issue of preventing the done key by not testing which key is pressed. It's also easily expandable by simply changing the regexp to match a different kind of zip code.

Categories

Resources