Detect double Ctrl keypress in JS - javascript

I have a custom CMS and would like to add a "shortcuts menu" triggered by the pressing of the Ctrl key twice within, say, 300 milliseconds.
I use prototype, so my starting point obviously is:
Event.observe(document, 'keypress', function(event)
{ if(event.keyCode == Event.KEY_XYZ) { show_shortcuts});
My approach at the moment would be populating a global variable with the current time in milliseconds, and checking on each keypress whether a keypress has happened less than 300 milliseconds ago.
But maybe there is a more elegant solution?

This should work. Maybe add some further checking if not some other key like Alt or Shift are pressed at the same time. Hope it is self explanatory, if not just ask and I provide clarification.
var dblCtrlKey = 0;
Event.observe(document, 'keydown', function(event) {
if (dblCtrlKey != 0 && event.ctrlKey) {
alert("Ok double ctrl");
dblCtrlKey = 0;
} else {
dblCtrlKey = setTimeout('dblCtrlKey = 0;', 300);
}
});
https://jsfiddle.net/3tc26g7x/

function doubleControlEvent() {
if (event.key === 'Control') {
timesCtrlClicked++
if (timesCtrlClicked >= 2) {
console.log('Double control')
// Double Crtl is clicked add your code here
}
setTimeout(() => (timesCtrlClicked = 0), 200)
}
}
let timesCtrlClicked = 0;
document.addEventListener('keyup', doubleControlEvent, true)

Related

Pure JavaScript to detect only Ctrl+Q shortcuts

I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)

How to change values of div when press key down

I have made divs in my HTML that I use to draw bars with CSS.
Now I want the to values change when the user presses the down arrow key.
This is my JavaScript:
var changeIdValue = function(id, value) {
document.getElementById(id).style.height = value;
};
window.addEventlistener("onkeydown", function(e){
if(e.keyCode == 40){
changeIdValue("balklongwaarde", "60px");
});
}
I don't understand why this is not working.
I know this has been answered already, but if you want to follow your original idea, here's the correct code (because Mritunjay's answer only works for one usage per page).
var changeIdValue = function (id, value) {
document.getElementById(id).style.height = value;
};
window.addEventListener('keydown', function (e) {
if (e.keyCode === 40) {
changeIdValue('balklongwaarde', '60px');
}
});
addEventListener is written with a capital L in Listener
'onkeydown' should be 'keydown' when used with the addEventListener function
You closed your brackets in the wrong order (close if, close function, close function call)
You can say something like this
window.onkeydown = function(e){
if(e.keyCode == 40)
changeIdValue("balklongwaard", "60px");
};

Keypress in backbone.js?

It looks like key-press can only be executed on a focus element? I don't fully buy into that, there has to be a way to execute a key-press event similar to a click event?
I have a view that works with one item at a time. I have a mouseenter - mouseleave function that adds a class to the item the mouse is over. When the item receives that class I want to be able to use a key-press event to run a function on that item.
Obviously this is a slight obstacle but Id like to find out what I need to do. Below is an example view.
var PlayerView = Backbone.View.extend({
tagName: 'div',
events: {
'click .points, .assists, span.rebounds, span.steals':'addStat',
'mouseenter': 'enter',
'mouseleave': 'leave',
'keypress': 'keyAction'
},
enter: function() {
this.$el.addClass('hover');
},
leave: function() {
this.$el.removeClass('hover');
},
keyAction: function(e) {
var code = e.keyCode || e.which;
if(code == 65) {
alert('add assist')
}
}
});
So there isn't much logic here, but I am thinking I would write something like this
keyAction: function(e) {
var code = e.keyCode || e.which;
if(code == 65) {
var addAssist = parseInt(this.model.get('assists')) + 1;
this.model.save({assists: addAssist});
}
}
Basically If I could figure out how to fire that keyAction method I should be good to go. So what are some caveats I am missing in executing some code like this? I am sure there are a few.
I do understand some of what is wrong with this code, it has no way of knowing when we run keypress in that view, I would have to add a conditional or something to find the active class, so when I execute the keypress it knows what model I am talking about, very vague description here but I get there is something wrong I am just not sure how to do this?
My solution
initialize: function() {
this.listenTo(this.model, "change", this.render);
_.bindAll(this, 'on_keypress');
$(document).bind('keydown', this.on_keypress);
},
enter: function(e) {
this.$el.addClass('hover');
},
leave: function(e) {
this.$el.removeClass('hover');
},
on_keypress: function(e) {
// A for assist
if(e.keyCode == 65) {
if(this.$el.hasClass('hover')) {
var addThis = parseInt(this.model.get('assists')) + 1;
this.model.save({assists: addThis});
}
}
// R for rebound
if(e.keyCode == 82) {
if(this.$el.hasClass('hover')) {
var addThis = parseInt(this.model.get('rebounds')) + 1;
this.model.save({rebounds: addThis});
}
}
// S for steal
if(e.keyCode == 83) {
if(this.$el.hasClass('hover')) {
var addThis = parseInt(this.model.get('steals')) + 1;
this.model.save({steals: addThis});
}
}
// 1 for one point
if(e.keyCode == 49) {
if(this.$el.hasClass('hover')) {
var addMake = parseInt(this.model.get('made_one')) + 1;
this.model.save({made_one: addMake});
var addOne = parseInt(this.model.get('points')) + 1;
this.model.save({points: addOne});
}
}
// 2 for two points
if(e.keyCode == 50) {
if(this.$el.hasClass('hover')) {
var addMake = parseInt(this.model.get('made_two')) + 1;
this.model.save({made_two: addMake});
var addTwo = parseInt(this.model.get('points')) + 2;
this.model.save({points: addTwo});
}
}
// 2 for two points
if(e.keyCode == 51) {
if(this.$el.hasClass('hover')) {
var addMake = parseInt(this.model.get('made_three')) + 1;
this.model.save({made_three: addMake});
var addThree = parseInt(this.model.get('points')) + 3;
this.model.save({points: addThree});
}
}
}
This is cool for my app because when the user hovers over the item the user can hit a key to add data, instead of clicking.
So you are only going to be able to listen to the keypress in whichever element that you have the listener set on (or its children). And the keypress event is only going to fire if the element is focused. So I think the best solution for you would be to set focus on the element you are hovering over, then you can listen for the keypress, or better yet, listen to keydown because it behaves in a more standard way cross browser.
Here is a working JSFiddle demonstrating this technique: http://jsfiddle.net/DfjF2/2/
Only certain form elements accept focus. You can add contenteditable or tabindex attributes to the element, and that should allow pretty much any element to receive focus, but then the keydown event won't actually get fired! This is a browser specific issue. In my experience, a <span> will cause keydown and keyup events to be fired in every browser I have tested (Chrome, Firefox, IE, Safari, Android browser, Silk). So in the jsfiddle I added a span inside the target element, put focus on that, and added the keydown event listener to it.
So if you added an empty <span> into your view, your code could look something like this:
var PlayerView = Backbone.View.extend({
tagName: 'div',
events: {
'click .points, .assists, span.rebounds, span.steals':'addStat',
'mouseenter': 'enter',
'mouseleave': 'leave',
'keydown': 'keyAction'
},
enter: function() {
this.$el.addClass('hover');
var span = this.$el.find('span');
span.attr('tabindex', '1').attr('contenteditable', 'true');
span.focus();
},
leave: function() {
this.$el.removeClass('hover');
var span = this.$el.find('span');
span.removeAttr('contenteditable').removeAttr('tabindex');
span.blur();
},
keyAction: function(e) {
var code = e.keyCode || e.which;
if(code == 65) {
alert('add assist')
}
}
});

Forbidding Apostrophe while typing in HTML textBox

I am looking for a simple maybe JS to forbid apostrophe onKeyUp or OnKeyPress kind of thing. For ex, every time user presses a key if it was apostrophe (Jame's Pizza) replace it with space. I don't want to process it in PHP
I found a code but it ties the JS to the textfield Name which I don't want. I need something global,
It's always better to prevent the keystroke than to retroactively delete it. To accomplish this, you need to intercept the keypress event (keyup is too late):
document.getElementById('yourTextBoxID').onkeypress = function () {
if (event.keyCode === 39) { // apostrophe
// prevent the keypress
return false;
}
};​
http://jsfiddle.net/TSB9r/
If you only want to stop the ' from appearing in the box but would like the keypress event to propagate to parent elements, replace the return false; with event.preventDefault();. (suggested by Eivind Eidheim Elseth in the comments)
Please find below functions. It grabs all of the input elements on the page and assigns keydown and keyup event handlers to each of them. If they detect an apostrophe, it will call the preventDefault() method..
function listen(event, elem, func) {
if (elem.addEventListener) return elem.addEventListener(event, func, false);
else elem.attachEvent('on' + event, func);
}
listen('load', window, function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
keyHandler(i);
}
function keyHandler(i) {
listen('keydown', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
listen('keyup', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
}
});

Different actions on multiple Keydown event

Okay, so my question (im hoping) is fairly simple. I want to know what to do so that I can create different events for the same keycode. For instance Id like to fade out a div and fade a new one in on the first keypress, then fade that one out and fade a new one in on keypress.
Thanks!
$(document).keydown(function() {
if (event.keyCode == '40') {
$('.div-1').fadeOut("slow")
$('.div-2').fadeIn("slow")
// I'd like this event to occur on the Second keydown
$('.div-2').fadeOut("slow")
$('.div-3').fadeIn("slow")
}
});
try
var hits = 0;
$(document).keydown(function() {
if (event.keyCode == '40') {
hits++;
if (hits % 2 == 0) {
// I'd like this event to occur on the Second keydown
$('.div-2').fadeOut("slow");
$('.div-3').fadeIn("slow");
} else {
$('.div-1').fadeOut("slow");
$('.div-2').fadeIn("slow");
}
});
The only solution I can see is create local variable. In your case (slodeshow) you need to count each keydown and parse div class.
var hits = 0;
$(document).keydown(function() {
if (event.keyCode == '40') {
$('.div-' + hits).fadeOut("slow")
$('.div-' + (hits + 1)).fadeIn("slow")
hits++;
}
});

Categories

Resources