I'd like to trigger an event once after key down and a different event only after the down arrow key has been released, like so:
$('body').keydown(function (e)
{
if(e.keyCode==40)
{
//do something
}
$('body').keyup(function (d)
{
if(d.keyCode==40)
{
//do something else
}
}
}
This code only functions partially. The keydown is triggered continuously as the down arrow key is held.
I have a setInterval whose refresh rate I'm altering when I hold the arrow key. Unforunately setTimeOut isn't an option in this situation.
So my code looks something like this:
clearInterval(interval);
refresh = 100;
interval();
$('body').keydown(function (e) {
if(e.keyCode==40) {
//do something
}
return false;
})
.keyup(function(e) {
if(e.keyCode==40) {
//do something else
}
return false;
});
$('body').on('keyup', function (e) {
if(e.keyCode==40) {
//do something
}
// after first keyup set to handle next keydown only once:
$(this).one('keydown', function(e) {
if(e.keyCode==40) {
//do something else
}
});
});
If you need exactly trigger the event and not handle as it's in your example, then you need to use $.trigger() method.
If you want to do some action only once while the key remains pressed, simply keep track of that:
var arrowKeyDown = false;
$('body').keydown(function(e) {
if (e.which == 40 && !arrowKeyDown) {
arrowKeyDown = true;
// ...
}
});
$('body').keyup(function(e) {
if (e.which == 40) {
arrowKeyDown = false;
}
});
Demo: http://jsfiddle.net/utfwQ/
$('body').keydown(function (e)
{
console.log('down');
}).keyup(function(e){console.log('up')});
If you really need to remove the keyup listener when you're done,
http://jsfiddle.net/CgmCT/
document.body.addEventListener('keydown', function (e) {
if(e.keyCode === 40){
console.log('key 40 down');
// key down code
document.body.addEventListener('keyup', function listener(d){
if(d.keyCode === 40){
document.body.removeEventListener('keyup', listener, true);
console.log('key 40 up');
// key up code
}
}, true);
}
}, true);
Related
Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);
I have 2 events, a keydown and a click. I would like to put them into a single function and when the function is called, whichever event was fired would do what it's supposed to.
Example:
var close = function () {
$('.alert').remove();
};
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
//27 = ESC
close();
}
});
$('.alertBG').on('click', function () {
close();
});
I can't think of a way to get the document and .alertBG parts to play nicely. (Fiddle)
Don't. Your functions are too different. You have already factored the reusable parts of them out into a close function that you call from both. This is the best way to do it.
If you really wanted to, then you would have to bind a click/keydown handler to document and test the type of event and the element.
$(document).on("keydown click", function (event) {
if (
(event.type === "keydown" && event.keyCode === 27) || (event.type === "click" && (
$(event.target).is(".alertBG") || $(event.target).parents(".alertBG").length))) {
close();
}
});
As you can see, it's much cleaner just to bind your event handlers separately when there are so many differences between them.
Do you mean something like this?
function handler(event) {
if(event.type === "click") {
close();
} else if(event.type === "keydown") {
if (event.keyCode === 27) {
//27 = ESC
close();
}
}
}
$(document).on('keydown', handler);
$('.alertBG').on('click', handler);
Anything like this ?
function myFunc(method){
if(method == "one"){
// do anything
}
else if(method == "other"){
// do other thing
}
}
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
myFunc("one");
}
});
$('.alertBG').on('click', function () {
myFunc("other");
});
I'm trying to detect an Enter key press event when a button has been clicked.
I'm new in javascript and don't know the good way to go...
HTML:
<div id="div"> Only execute javascript on click, not enter key press </div>
JAVASCRIPT:
$("#div").click(function () {
/* IF ENTER KEY PRESSED, RETURN FALSE */
$("#div").keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
alert('clicked');
}
});
/* Div has been clicked, continue code... */
});
This doesn't work...
Maybe there is a better way:
$("#div").MOUSE_CLICK_EVENT(function () {});
You need to stopPropagation like:
$('#div').keydown(function(event){
if (event.which == '13') {
event.preventDefault();
event.stopPropagation();
}
});
stopPropagation: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
As others have noted, you need stopPropagation in addition to preventDefault, and you should be listening for the keydown event rather than keypress.
The pure JavaScript way to do this is:
document.getElementById('div').onkeydown = function (evt) {
if (evt.which === 13) {
evt.preventDefault();
evt.stopPropagation();
return false;
}
};
document.getElementById('div').onclick = function (evt) {
// do whatever you want here
};
try this if still needs anybody. Quick solution.
$("form").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
Also you need to consider 3 key events: keydown, keypress and keyup.
$("#ID").keydown (function (e) {
if ( e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keyup (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keypress (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.
I have to use javascript to make links instead of for several unimportant reasons, and I want for it to behave like even though im not using it. Not the affects thats easy, but I want to be able to hold down shift while clicking to open a new window and to open it in a new tab if they are holding down ctrl. How would I do this? Also, it has to be compatible with IE9.
[edit] Also, this is going to be in an iframe
I guess you want something like this:
JSFiddle
http://jsfiddle.net/MXuVY/3/
JavaScript
var ctrlPressed = false;
$('#link').click(function () {
var link = 'http://stackoverflow.com/';
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
$(document).keydown(function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
HTML
<span id="link">Link to stackoverflow</span>
Version without jQuery
JSFiddle
http://jsfiddle.net/MXuVY/6/
JavaScript
function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
} else {
el['on' + eType] = fn;
}
}
var ctrlPressed = false,
a = document.getElementById('link'),
link = 'http://stackoverflow.com/';
addEvent(a, 'click', function () {
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
addEvent(document, 'keydown', function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
addEvent(document, 'keyup', function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
Bind a keystroke event listener to window or document and use it's callback function to do whatever you need.
If you use jquery, its a bit easier to make a more reliable keystroke listener, imho. http://blog.cnizz.com/2008/10/27/javascript-key-listener/
So, this is what you want: http://jsfiddle.net/DerekL/V8yzF/show
$("a").click(function(ev) {
if (ev.ctrlKey) { //If ctrl
window.open(this.attr("href"));
retrun false;
} else if (ev.shiftKey) { //If shift
window.open(this.attr("href"),"_blank", "width=400,height=300");
retrun false;
} else { //If nothing
//do nothing
}
});