Javascript Tab keydown when pressed and hold tab, it flickers infinitely - javascript

I have written some simple keydown event handler on a group of inputs, like such
$('.a, .b, .c').on('keydown', function (e) {
switch(keycode) {
case 9:
e.preventDefault();
e.stopPropagation();
if($('.a'))
// focus next
else if($('.b'))
// focus next
....
break;
}
})
However when I press the tab and hold, the cursor flickers infinitely and the event does not fire anymore, I have to focus outside the window and comeback for it to stop.
Have been trying to figure it out for many a days now, can anyone shine some light on how do I stop this behaviour?
Ok guys i have edited the code and reproduced the error in which i found out the mistake and fixed the issue.. Here is the code producing the effect.
$(document).ready(function(){
$('.c, .d').on('focus', function (e) {
if (e.relatedTarget) {
var v = $(this).val();
var n = v.toString().replace(/,/g, "");
$(this).val(n);
var $elementThis = $(this);
setTimeout(function () { $elementThis.select(); }, 50);
}
});
$('.a, .b').on('focus', function (e) {
if (e.relatedTarget) {
var $elementThis = $(this);
setTimeout(function () { $elementThis.select(); }, 50);
}
});
$('.a, .b, .c, .d').on('keydown', function(e) {
var keycode = e.charCode || e.keyCode || 0;
switch (keycode) {
case 9:
{
e.preventDefault();
e.stopImmediatePropagation();
if ($(this).hasClass('a')) { $('.b').focus(); }
else if ($(this).hasClass('b')) { $('.c').focus(); }
else if ($(this).hasClass('c')) { $('.d').focus(); }
else if ($(this).hasClass('d')) { $('.a').focus(); }
break;
}
}
})
});
The part that is giving me the problem is the
setTimeout(function () { $elementThis.select(); }, 50);
causing it to flicker non-stop.
I am finding an alternative to it. Any suggestions are welcome.
And please remove the downvote. I hope this insight will be of help to someone in the future.

You have a mistake. It should be e.keyCode:
$('.a, .b, .c').on('keydown', function (e) {
switch(e.keyCode) { // Change this. Also better to check if `e.which`
case 9:
e.preventDefault(); // Change this
e.stopPropagation();
if($('.a'))
;//focus next
else if($('.b'))
;//focus next
....
break;
}
});

The full version:
$('.a, .b, .c').on('keydown', function (e) {
var charCode = e.which || e.keyCode;
switch(charCode) {
case 9:
e.preventDefault();
e.stopPropagation();
if($('.a'))
;//focus next
else if($('.b'))
;//focus next
....
break;
}
});

key code should be accessed like this e.keyCode
$('.a, .b, .c').on('keydown', function (e) {
switch(e.keyCode)
{
case 9:
e.preventDefault();
e.stopPropagation();
if($('.a'))
//focus next
else if($('.b'))
//focus next
....
break;
}
})

Related

How to disable up and down arrow keys

I am trying to disable arrow up and down function for a selection list field. I have searched and tried all the options but could not disable. When alerting with the keys it is working but when I try to disable it does not work. Is there any updates related with browsers
My Chrome Version: 89.0.4389.128 (Official Build) (64-bit)
// we are closing the arrow keys for selection
$(function()
{
$('.form-contact').on('keyup',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
Last code something like this. it does not prevent arrow up or down to the list but it prevents selection by enter from the list. So better than nothing. Still open my question.
$('.form-contact,.form-company,.form-address,.form-postcode,.form-phone,.form-email').on('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Instead of keyup, use keydown event
$(function()
{
$('.form-contact').on('keydown',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
This might be helpful:
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
Found it here Disable arrow key scrolling in users browser

CanJS right click event

how can I bind a right click event in CanJS?
I've attempted the following, but I guess click only captures left clicks (as ev.which doesn't log 3 on right clicks).
'.btn click': function (el, ev) {
console.log(ev.which);
switch(ev.which) {
case 1:
var val = 1;
break;
case 3:
ev.preventDefault();
var val = -1;
break;
}
var item = can.data(el.closest('tr'), 'item');
item.attr('rel', item.rel + val);
}
I don't know what CanJS is, but I would use oncontextmenu:
elem.oncontextmenu = function(e) {
e = e || window.event;
if(e.preventDefault) e.preventDefault();
e.returnValue = false;
// Your code
};
I think you were looking for contextmenu event: https://developer.mozilla.org/en/docs/Web/Events/contextmenu
You can use this in CanJS events:
'.btn contextmenu': function (el, ev) {
// your code
}

jQuery wait for keyup after keydown

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);​

Detecting keystrokes without textboxes?

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

JavaScript key listener disabled when inside a text form

I have a key listener assigned to the arrow keys to navigate a slideshow. But I want to disable the key listener, temporarily, while a user is typing inside an input field. How can I do that? My current code looks like this:
//Listen to the keys
function checkKey(e) {
switch (e.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');;
break;
}
}
if (jQuery.browser.mozilla) {
jQuery(document).keypress (checkKey);
} else {
jQuery(document).keydown (checkKey);
}
First, there's no need for the browser check. For checking arrow keys, just use the keydown event for all keys.
Second, I suggest (as Sean Hogan did) checking the target of the event before doing the slideshow stuff. The following will work on all mainstream desktop browsers:
document.body.onkeydown = function(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
var targetTagName = (target.nodeType == 1) ? target.nodeName.toUpperCase() : "";
if ( !/INPUT|SELECT|TEXTAREA/.test(targetTagName) ) {
switch (evt.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');
break;
}
}
}
A bit ugly, but should work:
var moz = jQuery.browser.mozilla;
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
jQuery("#myInput").focus(function() {
if (moz) {
jQuery(document).unbind("keypress");
} else {
jQuery(document).unbind("keydown");
}
}).blur(function() {
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
});
If the focus is on an input element then that element will be the target for key events.
So you could just do a check on event.target.tagName.
e.g.
function checkKey(e) {
switch (e.target.tagName) {
case "INPUT": case "SELECT": case "TEXTAREA": return;
}
// rest of your handler goes here ...
}
Add onfocus and onblur event to the input field and set a global variable value. Check for that global variable in the begining of your checkKey event handler.
<input type="textbox" onfocus="window.inTextBox = true;" onblur="window.inTextBox = false;" />
function checkKey(e) {
if (!window.inTextBox)
{
...
}
}
I really like the simplicity of Ilya Volodin's suggestion, but I would set the event handler in the script and not embed it into the html:
var textFocus = false;
$("textbox").focus(function() {
textFocus = true;
});
$("textbox").blur(function() {
textFocus = false;
});
function navKeys() {
if (textFocus) {
return false;
} else {
......
}
}
This would be even simpler if jquery had :focus as a selector.
function navKeys() {
if ($("textbox:focus") {
return false;
} else {
......
}
}
But that is just hypothetical code at this point.

Categories

Resources