boolean flag in javascript is not checking properly - javascript

i've created a sample application which checks when i press a key or mouse, but the problem is when mouse or when key is pressed it prints the console "Enter is pressed" and "Enter is not pressed some Mouse event is clicked", that boolean checking is not working properly i think so,
can anyone please tell me some solution
$('#adminPanel').bind("searchMaster", function(event, data)
{
var press = true;
$(this).keypress(function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13)
{
console.log("Enter is pressed");
press = false;
}
});
if(press)
{
console.log("Enter is not pressed, some Mouse event is clicked");
// some other action to be triggered if key is not pressed
}
});

The problem is, (a) that you register the keypress event inside the click callback and (b) that you set press to false, if is pressed and (c) that you never reset the value of press every time you click with the mouse.
I suggest you split the two callbacks up and move press outside of the callbacks. In the example press => enterPressed. The enterPressed and the callbacks are wrapped in an IIFE to not poluted the global namespace.
(function () {
// by default, "enter" is not pressed
var enterPressed = false;
// Suppose this event is triggered by mouse clicks
$("#adminPanel").bind("searchMaster", function (event, data) {
if (!enterPressed) {
// Handle Mouse Click (no "enter" pressed here)
}
});
// This callback will be triggered if you press a key
// and if you release a key
$("#adminPanel").on("keydown keyup", function (e) {
var code = e.keyCode ? e.keyCode : e.which;
// check if the pressed/released key was "enter"
if (code === 13) {
enterPressed = !enterPressed;
}
});
})();

Related

To open a new web page after pressing the enter key 3 times

I need the script for functioning the window.location only after pressing the ENTER key 3 or n times.
This is my current code and i am trying to modify it. Need help, still.
function KeyPress(f) {
var event = window.event? event : f
if (event.keyCode == 13)
window.location = './index.html';
}
document.onkeypress = KeyPress;
Following your instructions, after three press to the key ENTER, it should run the code that will call window.location. In this example, I'm using console.log to prove it is doing what you asking.
Note: When you run it, you need to click with the mouse where it says "Press Enter 3 times.". In this way, the browser will focus on that section. Then, you can press the ENTER key three times.
document.addEventListener("keyup", (e) => enterKeyPressed(e))
let counter = 1;
function enterKeyPressed(event) {
console.log("Key", event.keyCode, " Pressed:", counter);
if (event.keyCode == 13 && counter == 3) {
console.log("Enter key is pressed");
// window.location = "<url you want to go>";
return true;
}
counter++;
return false;
}
Press Enter 3 times.
Check the log.

is there a function to do on a specific keypress instead of click

i was wondering if there is a function i could use instead of using a mouse click as i have set keybinds to whenever i press it it does it on my pc , here is my code i am using for a broswer script on tampermonkey,
}
$('.pagination.prev').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
$('.pagination.next').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
}
instead of using mouse click on the next button and previous button i would like it to use b key as previous and n key as next
thanks in advance for help really appriciate it
Handling a 'keydown' event is rather simple.
You simply listen for the event, then check for the key you are interested in.
For example, this code listens for the keys "b" and "n":
const pre = document.querySelector('pre');
pre.innerText = "";
window.addEventListener('keydown', event => {
// console.log('keydown event:', event);
pre.innerText += `keydown event.key: "${event.key}"\n`;
if (event.key === 'b') {
alert('You pressed "b"');
} else if (event.key === 'n') {
alert('You pressed "n"');
}
});
document.querySelector('button').onclick = () => {pre.innerText = ""};
<h4>Logging 'keydown' Events</h4>
<button>Clear Log</button>
<pre></pre>
Consideratons
As Stephen P mentions, there are some things to be aware of when using 'keydown' events:
holding a key sends repeated keydown events
non-printing keys such as Shift and Control send keydown events
Shift+N produces uppercase N, not lowercase 'n'

Using shift with left click for event without jQuery

My goal is to press a button and perform an action only when the shift key is also pressed. However, it doesn't even seem to recognize the shift key right now. Currently it works with only the right click but like I said, I want it to work with right click + shift.
button.addEventListener("oncontextmenu", function(e) {
document.addEventListener("keydown", function(e) {
console.log("this string won't show");
if (e.keyCode == 16) {
console.log("this string won't show either");
} else {
console.log(e.keyCode); // again it won't show
}
});
rightShiftClick(e); // this will execute perfectly.
});
The event object tells you if the shift key is pressed and there is no "on" when you are attaching the event.
button.addEventListener("contextmenu", function(e) {
console.log(e.shiftKey);
});

Use a preventdefault to get out of the loop after pressing Enter key

This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})

jQuery handling keypress combinations

I know that when keypress event occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypress combinations through jQuery like ctrl + D ..etc?
In the following code I tried to do something like :
$(document).on("keypress", function(e) {
if( /* what condition i can give here */ )
alert("you pressed cntrl + Del");
});
jQuery already handles this for you:
if ( e.ctrlKey && ( e.which === 46 ) ) {
console.log( "You pressed CTRL + Del" );
}
I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:
NOTE: This example is catching ctrl + space combination, but you can easily change it to any other keys.
var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
$(document).keydown(function(e) {
if (e.ctrlKey) { //If it's ctrl key
ctrlPressed = true; //Set variable to true
}
}).keyup(function(e) { //If user releases ctrl button
if (e.ctrlKey) {
ctrlPressed = false; //Set it to false
}
}); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want
$(document).keydown(function(e) { //For any other keypress event
if (e.which == 32) { //Checking if it's space button
if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
myFunc(); //Do anything you want
ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
}
}
})

Categories

Resources