I have a problem. I want to stop keypress event when space is pressed, then I want to do something and finally I need to "restart" this function. It is possibile? How can I do this?
Thank you in advance
$(document).keypress(function(e) {
if(e.keyCode == 32)
// stop keypress function
// do something
// restart keypress function
}
I believe you have two choices.
Disable the handler:
$(document).on('keypress', function keypressHandler(e) {
//disable handler
$(document).off('keypress');
//do stuff
//enable keypress handler
$(document).on('keypress', keypressHandler);
});
Use a flag:
var keyHandlerActive = true;
$(document).on('keypress', function(e) {
if (!keyHandlerActive) { return; }
keyHandlerActive = false;
//do stuff
keyHandlerActive = true;
});
Try one of these functions:
e.stopPropagation();
OR
e.preventDefault();
Full code:
$(document).keypress(function(e) {
if (e.keyCode == 32) {
e.preventDefault(); // e.stopPropagation();
}
})
Your turn off condition is space, but turning back on condition is not mentioned.. so I am using a timer below.. change it as you like
To try the demo,
Type any key except space to see it get logged
Press space to turn off for 10 seconds (or change code to make it until a process complete)
function turns On after 10 seconds
The function simply turns off (logical off as bind/rebind might become a pain if overused) for 10 seconds when space is pressed.
var logicalOff = false;
$(document).keypress(function(e) {
if (logicalOff) { return true; } //well we just ignore and return until turned On
$('div').text(e.which);
if(e.which == 32) {
logicalOff = true; // stop keypress function
setTimeout(function () { // restart keypress function
logicalOff = false;
$('div').text("turned on now");
}, 10000);
$('div').text("turned off for 10 seconds");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Well, you can play with it like this as I have added two buttons for both situations and by default the SPACE will be disabled. Check it out please:
HTML
<input id="myinput" type="text">
<input id="space_flag" type="hidden" value="0">
<br/>
<input id="enable_space" type="button" value="Enable Space">
<br/>
<input id="disable_space" type="button" value="Disable Space">
JQuery
$(function(){
$("#myinput").keypress(function(event){
if(event.keyCode == 32 && $("#space_flag").val()==0){
return false;
}
});
$("#enable_space").click(function(event){
$("#space_flag").val(1);
});
$("#disable_space").click(function(event){
$("#space_flag").val(0);
});
});
Working example http://jsfiddle.net/1pn4cLak/
Related
First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}
This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.
I know how to trigger a function with a textbox:
<input onkeyup="if (event.keyCode == 13) check(this)" type="text">
But what if I'm not focused on any textboxes, but I still need to call a js function with a space button for example?
Particular context:
I'm trying to write an interactive test, and I want users to be able to switch to the next question not only with the button on the page:
<button id="nextButton" onclick="nextQuestion()">Next</button>
but also with a space button, so they can change questions more quickly. To arrange that, I need to call the nextQuestion() function everytime a user presses space on a keyboard.
Try binding the event to the window
window.onkeyup = function(event){
if (event.keyCode== 32) nextQuestion()
}
With jquery you can do something like
$(window).keypress(function(e) {
if (e.keyCode == 32 || e.keyCode == 0) {
nextQuestion()
}
});
or if you prefer vanilla javascript i recommend
window.addEventListener("keyup", keyPressed(e));
function keyPressed(e) {
if(e.keyCode == 32) nextQuestion();
}
can call keyup on body tag or window object
$("body").keyup(function(event){
alert("KeyCode is : " + event.keyCode);
if(e.keyCode == 32){ nextQuestion()}
});
I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.
Below is the the code I am using for the spacebar on the game's page.
The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
};
thanks
There are many ways you could do this, here's one:
var hit = document.getElementById("hit");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
if (e.currentTarget.type === 'input') { //Or whatever check you want here
// Do things for your searchBox
return; //Prevent rest of the function from running
}
e.preventDefault();
hit.click();
}
};
Inside the above function you must check if the cursor is in your search box, and if it is then skip the rest of the function
Have rewritten your code as below, hope it helps
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (document.activeElement.nodeName != 'TEXTAREA' && document.activeElement.nodeName != 'INPUT') {
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
}
};
Cheers mate!
You can stop the 'keydown' events from the search bar from propagating upwards by calling event.stopPropagation():
document.addEventListener('keydown', function(e) {
console.log('hit!');
e.preventDefault();
});
let search = document.getElementById("search");
search.addEventListener('keydown', function(e) {
console.log("search!");
e.stopPropagation();
});
<form id="search"><input name="query" type="text"><input type="submit" value="search"></form>
My script execute some actions (like stop one audio player) in case the user press the space bar:
$('html').keydown(function(e){
if(e.keyCode == 32){
// Stop the audio player
}
}
But the problem comes when a user tries to write a message in the textarea because the previous function executes (and it's very annoying)... How can I do to not execute the function, in case the user is writing a message on a textarea or other elements?
You need to skip when user is focussing some control, this example will prevent the player to stop if user i typing in a text area.
$(function () {
$(document).keypress(function (e, f) {
var tagName = e.target.tagName.toLowerCase();
if (tagName != 'textarea') {
if (e.keyCode == 32) {
console.log('Stop Playing');
}
}
});
});
Hopw this helps.
Try this,
$('#textAreaId').keypress(function(e){
e.preventDefault();
});
Use stopPropagation method on event object when space bar pressed on textarea.
$(document).ready(function(){
$("#testTextArea").keydown(function(e){
if(e.keyCode == 32){
e.stopPropagation();
}
});
$("#container").keydown(function(e){
if(e.keyCode == 32){
alert('Player Stoped/Started')
}
});
})
fiddle : http://jsfiddle.net/b0u3z8pg/16/
Try This :)
$('html').keydown(function(e) {
if(e.keyCode == 32){
// stop the music player
}
});
$('input, textarea').keydown(function(e) {
e.stopPropagation();
});
Something like this:
The code inside the if statement only triggers if you are not focused inside a text area or input.
jsfiddle demo
HTML:
<textarea></textarea>
<input type="text">
jQuery:
var exclude = $("textarea, input");
$('html').on("keydown", function( e ) {
if ( e.keyCode == 32 && !exclude.is(':focus') ) {
console.log( 'Space pressed outside input or text area' );
}
});
You should check the sender of the event, if the sender is other controls then the audio player then ignore the call, otherwise stop the player.
$('html').keydown(function(e){
var senderID = $(event.target).attr('id');
if(senderID == 'myAudioPlayerID' && e.keyCode == 32){
// Stop the audio player
}
}
I'm trying to change the focus whenever a user presses tab on the last field. I want to set the focus on to another input field.
I have the following javascript code:
$("#input2").keydown(
function()
{
if(event.which == 9)
{
$("#input1").focus();
}
}
);
And this is my trial html code:
<div id="inputArea1">
<input id="input1" />
<input id="input2" />
</div>
It seems to work with keyup (the changing the focus part) but then again I don't get what I want with keyup..
What am I missing?
You need to stop the event, by returning false. If you do not, the basic browser event is fired after you switched to input1, which means the focus is back at input2.
For example:
$("#input2").keydown(function(e){
if(e.which == 9){
$("#input1").focus();
return false;
}
});
Yes, those guys get to it before me.
Another jQuery way is to use event.preventDefault()
$("#input2").keydown(
function()
{
if(event.which == 9)
{
event.preventDefault();
$("#input1").focus();
}
}
);
Live example:
http://jsfiddle.net/ebGZc/1/
You probably need to cancel the default handling of the event by the browser by returning false from your keydown handler, like this (live example):
$("#input2").keydown(
function(event)
{
if(event.which == 9)
{
$("#input1").focus();
return false;
}
}
);