How to catch keypress and mouse up at the same time - javascript

I can toogle the ctrlBtn["pressed"] to true when I press CTRL or ALT key on Mac. (inspecting by console.log)
However, when I trigger the mouse up it couldn't enter the saveWord(selected). ctrlBtn["pressed"] still stays false.
What a good practice to catch the keypress and mouse up at the same time.
I'm writing a chrome extension currently. The whole script is here! https://gist.github.com/weichenghsu/4bbb2d1b6c3d34d55a942c3c6713fa89
Thanks!
window.addEventListener('load', function () {
...
document.body.addEventListener('mouseup', function (e) {
var selection = window.getSelection();
var selected = selection.toString().trim();
if (selected) {
console.log(ctrlBtn);
console.log(ctrlBtn["pressed"]);
if (ctrlBtn["pressed"] == true) {
saveWord(selected);
}
updateHighlighter();
}
});
window.addEventListener('keyup', function (e) {
ctrlBtn["pressed"] = false;
});
window.addEventListener('keydown', function (e) {
console.log(e.keyCode);
if (e.keyCode == 17 || e.keyCode == 18) {
ctrlBtn["pressed"] = true;
}
e.preventDefault();
return false;
});

Related

Executing Different Parts of JavaScript Code by Pressing Key and Clicking

I have code for 3 different task which I want to execute by clicking and pressing a key, so there will be 3 different combination of clicking and pressing. For example-
window.addEventListener("keydown", function(e){
if(e.keyCode === 16) {console.log('Yap! Shift works...');}
if(e.keyCode === 17) {console.log('Yap! Ctrl works...');
document.addEventListener('click',function (event) {
console.log(event.target.className);
}, false);
}
},false);
Now, when I press click shift key, I get related output, when I click Ctrl key and then click, I get the class name of the object I click on.
But the problem is, the output keeps coming as much I hold the key!! I want to execute the part of my code for once, and exactly when the key is pressed and a clicked is occurred.
How can I do that?
In general, how can I execute 3 part of code for three different tasks by clicking and pressing efficiently?
Adding an event handler while handing an event, is often the wrong way to solve a problem. Imagine how you will accumulate adding handlers... in your case there will eventually be many bindings to the same click handler.
It is better to bind the handlers you need immediately, and then work with keeping state on what exactly needs to happen while handling the event.
In these key handlers (keydown, keyup), keep track of whether the Shift/Control keys are depressed or not.
Also, use e.key as e.keyCode is deprecated.
Here is how that could work:
let keys = {
"Shift": false,
"Control": false
};
function keyToggle(e) {
if (!(e.key in keys)) return; // not ctrl or shift
let isKeyDown = e.type === "keydown";
if (isKeyDown === keys[e.key]) return; // key position did not change
keys[e.key] = isKeyDown;
console.log(e.key + (isKeyDown ? " pressed" : " released"));
}
document.addEventListener("keydown", keyToggle, false);
document.addEventListener("keyup", keyToggle, false);
document.addEventListener('click', function (e) {
if (keys["Control"]) console.log(event.target.className);
}, false);
<main class="main">Main</main>
<aside class="aside">Aside</aside>
As you addEventListener you can also removeEventListener.
For that you need a reference to your event handler, so you cannot use anonymous functions, but named functions or functions stored in a variable.
Edit
Here is an example of using CTRL+click:
// CTRL + CLICK implementation
let hasCtrl = false;
// Store the handler in a constant or variable
const handleClick = function(event) {
console.log(event.target.className);
}
// Use named function
function handleKeyDown(e) {
if (e.keyCode === 16) {
console.log('Yap! Shift works...');
}
}
const setCtrlInactive = (e) => {
if (!hasCtrl && e.keyCode === 17) {
console.log('Nope! Ctrl does not work...');
document.removeEventListener('click', handleClick);
hasCtrl = true;
}
}
const setCtrlActive = (e) => {
if (hasCtrl && e.keyCode === 17) {
console.log('Yap! Ctrl works...');
document.addEventListener('click', handleClick);
hasCtrl = false;
}
}
document.addEventListener("keyup", setCtrlInactive);
document.addEventListener("keydown", setCtrlActive);
document.addEventListener("keydown", handleKeyDown);
<main class="main">Main</main>
<aside class="aside">Aside</aside>
Well you can easily create an variable to lock it:
var locked = false;
window.addEventListener("keydown", function(e){
if(e.keyCode === 16 && !locked) {console.log('Yap! Shift works...'); locked =
true;}
if(e.keyCode === 17 && !locked ) {console.log('Yap! Ctrl works...');
locked = true;
}
},false);
document.addEventListener('click',function (event) {
if(locked){
// do something
console.log(event.target.className);
}
}, false);
window.addEventListener("keyup", function(){
locked = false;
}
That's because you called addEventListener('click') in the keydown event handler.
let ctrl = false;
window.addEventListener("keydown", function(e) {
if (e.keyCode === 16) {
console.log('Yap! Shift works...');
}
if (e.keyCode === 17 && ctrl === false) {
console.log('Yap! Ctrl works...');
ctrl = true;
}
});
window.addEventListener("keyup", function(e) {
if (e.keyCode === 17) {
ctrl = false;
}
});
document.addEventListener('click', function(event) {
if (ctrl) {
console.log(event.target.className);
}
}, false);
Instead, you should use keyup event and flag variable.

how to stop keydown function after click a button

i have js code when i press key 38, 40 13 those function works respectively.
but what i want to do is ,when i click this button keydown function block will be disable,
and when i hover this button this keydown function block will be enable.
$(document).keydown(function(e){
if (e.keyCode == 38) {
verticalSlideDown();
//console.log("pressed key for Down : "+e.keyCode);
}
if (e.keyCode == 40) {
verticalSlideUp();
//console.log("pressed key for Up: "+e.keyCode);
}
if (e.keyCode === 13) {
var div= $(".scroll-inner-container");
//console.log("pressed key for stop : "+e.keyCode);
div.stop();
}
});
this is my html button:
<button class="keyboard-btn">click here</button>
Just create a flag.
Enabled on hover, disabled on click.
var controlsEnabled = false;
$(myButton).hover(function () {
controlsEnabled = true;
});
$(myButton).on('click', function () {
controlsEnabled = false;
});
$(document).keydown(function (event) {
if (controlsEnabled)
{
// rest of code here
}
});

prevent default 'F1' event in iE11

When the user press F1 key,I am planning to display our application help and suppress default action.
I tried with different options not to show help popup of IE.
Here is my Code:
document.addEventListener('keydown', function (e) {
if (e.key === 'F1' || e.keyCode == 112) {
e.cancelBubble = true;
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
//my help menu code goes here
}
});
Please let me know how can i achieve in showing the help page of my application instead of IE help.
I am using IE11 version.
You could subscribe to the window.onhelp event:
window.onhelp =function() {
alert();
return false;
}
Try doing this
<script>
$(document).ready(function () {
removedefaulthelp();
function removedefaulthelp()
{
window.onhelp = function () {
return false;
alert();
}
}
document.addEventListener('keydown', function (e) {
if (e.key === 'F1' || e.keyCode == 112) {
removedefaulthelp();
e.cancelBubble = true;
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
//my help menu code goes here
}
});
}
</script>
Refer this for more information.
Here is an example similar to Sukanya's answer, but my solution shows how to extend for the F2-F12 keys, and purposely disregards F-combination keys, such a CTRL + F1.
<html>
<head>
<!-- Note: reference your own JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<h1>F-key trap example</h1>
<div><h2>Example: Press the 'F1' key to open help</h2></div>
<script type="text/javascript">
//uncomment to prevent on startup
//removeDefaultFunction();
/** Prevents the default function such as the help pop-up **/
function removeDefaultFunction()
{
window.onhelp = function () { return false; }
}
/** use keydown event and trap only the F-key,
but not combinations with SHIFT/CTRL/ALT **/
$(window).bind('keydown', function(e) {
//This is the F1 key code, but NOT with SHIFT/CTRL/ALT
var keyCode = e.keyCode || e.which;
if((keyCode == 112 || e.key == 'F1') &&
!(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
{
// prevent code starts here:
removeDefaultFunction();
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
// Open help window here instead of alert
alert('F1 Help key opened, ' + keyCode);
}
// Add other F-keys here:
else if((keyCode == 113 || e.key == 'F2') &&
!(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
{
// prevent code starts here:
removeDefaultFunction();
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
// Do something else for F2
alert('F2 key opened, ' + keyCode);
}
});
</script>
</body>
</html>

Preventing user from typing text into a text box but allowing paste keyboard shortcut

I was wondering if there was a way to disable all key-down events (such as typing text) while the text box element is selected/has focus but still allow the ctrl+v paste shortcut to be used. In other words I'd like to make it so the only way a user can enter any text into the box is by pasting it (either by using the context menu or by the ctrl+v).
Try this simple solution:
<input type="text" id="txtbox" />
$(document).ready(function () {
var ctrlKey = 17
var vKey = 86
$("#txtbox").keydown(function (e) {
if (!(e.ctrlKey && e.which == vkey)) {
return false;
}
});
});
DEMO
Here's the code, deactivate keydown, but keep Ctrl+v working.
http://jsfiddle.net/70h3zron/
var ctrlActive = false;
$('#idtext').keydown(function(e) {
if(ctrlActive)
{
if(event.which == 86) {
return true;
}
else
{
e.preventDefault();
return false;
}
}
else
{
if(event.which == 17)
ctrlActive = true;
else
{
e.preventDefault();
return false;
}
}
});
$('#idtext').keyup(function(e) {
if(event.which == 17) {
ctrlActive = false;
}
});
Use this in jQuery,
$('#yourTextElementId').keypress(function(){
return false;
)};
Demo

Mouse flicker when trying to use a non-modifier key and dragging

There's been a recent trend to use spacebar as a meta key while performing certain drag actions in more graphical apps.
The problem is that the mouse flickers while holding spacebar (or any non-modifier key) down and moving your mouse: http://jsfiddle.net/S3AJr/4/
Example code:
$(function() {
var count = 1,
isSpaceBarPressed = false;
$('body').on('keydown', function(e) {
e.preventDefault();
if (e.which === 32) {
isSpaceBarPressed = true;
}
});
$('body').on('keyup', function(e) {
e.preventDefault();
if (e.which === 32) {
isSpaceBarPressed = false;
}
});
$('body').on('mousemove', function(e) {
if (isSpaceBarPressed) {
e.preventDefault();
$('.pizza').text(count++);
}
});
});
Is there a way to fix this or am I limited to ctrl, alt, shift and meta?
Easy fix bro!
// note include underscore-min.js for our throttle function
$(function () {
var count = 1,
isSpaceBarPressed = false;
var throttledRender = _.throttle(function () {
$('.pizza').text(count);
}, 200);
$('body').on('keydown', function (e) {
e.preventDefault();
if (e.which === 32) {
isSpaceBarPressed = true;
}
});
$('body').on('keyup', function (e) {
e.preventDefault();
if (e.which === 32) {
isSpaceBarPressed = false;
}
});
$('body').on('mousemove', function (e) {
if (isSpaceBarPressed) {
e.preventDefault();
count++;
throttledRender();
}
});
});
The problem is that you are rendering WAY too often (every time the event fires). Instead, you want to increment your variable every time but only render periodically. See this forked fiddle using underscore's throttle function. If you prefer, there is a jQuery plugin for this too.

Categories