Using shift with left click for event without jQuery - javascript

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

Related

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'

How to have an event trigger every time a user presses a key in javascript

First of all, I'm new to Javascript. I would like to have an event repeat itself every time a user presses a key in Javascript. See the sample code below:
<script>
document.addEventListener('keydown', function(event){
if(event.keyCode == 39) {
document.write('Right was pressed');
}
})
</script>
When this code is run and the right arrow key is pressed, the statement is only printed once. I would like to have the event register multiple times, as many times as the user presses the key. Any suggestions?
The event is fired every time you press the key (and repeated if you hold the key down), but document.write() will every time override the content so it looks like nothing change, you could use innerHTML instead (just to see the effect) :
document.addEventListener('keydown', function(event){
if(event.keyCode == 39) {
//Not recommended as 'T.J. Crowder' mentioned in the comment
document.body.innerHTML += 'Right was pressed <br>';
}
})
You could use console.log() to debug and make sure the event was invoked :
document.addEventListener('keydown', function(event){
if(event.keyCode == 39) {
console.log('Right was pressed');
}
})
Actually it indeed triggered multiple times. The problem is document.write would clear the DOM.
This example works well for me.
script:
var counter = 0;
document.addEventListener('keydown', function(event){
if(event.keyCode == 39){
++counter;
document.getElementById("demo").innerHTML = "Key downed " + counter;
}
});
html:
<p id="demo">
</p>

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

Why is tab keypress causing focus change also triggering keyup event?

Pressing the tab key which triggers a focus change is also received by the input receiving the focus as a keyup.
a: <input type='text'/><br/>
b: <input type='text' onkeyup='alert("wtf?")'/><br/>
http://jsfiddle.net/59SnP/
As my control also uses tab (not in the example), I would want the focus related keyup event being consumed (but I want to receive other non-focus-change related tab events). I tried to research the rationale behind the current behavior but found nothing. The question: Where is this current behavior specified (event not consumed by focus change), and what would be a cross-browser workaround to force consuming it. Thx.
You can try this. I changed your keyup event in your input :
<input type='text' onkeyup="if(!tabPressed){ alert('This is it !'); }"/>
And I added a little event handler which will raise a flag when the tab button is pressed :
var tabPressed = false;
document.addEventListener('keydown', function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
}, false);
Based on Nathan's insight, here is a fully working example:
// First part of Nathan's HACK (set a sentinel when a focus changing tab has happened)
var tabPressed = false;
// remove this listener to break the functionality
$(document).on("keydown", function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
});
// The listener on the client input that would kill the keyup tab event upon focus change
$("#magic").on("keyup", function(e) {
if (tabPressed && e.keyCode==9) {
tabPressed = false; // reset the sentinel
e.stopImmediatePropagation()
e.preventDefault()
}
})
And here is the second part, which is a simple skeleton of something meaningful. We disable TAB inside the input, and log it as we do with other keyups:
$("#magic").on("keydown", function(e) {
if (e.keyCode==9) {
e.preventDefault()
e.stopPropagation()
}
})
$("#magic").on("keyup", function(e) {
$(this).val($(this).val() + " " + e.keyCode)
e.stopPropagation()
e.preventDefault()
})
The HTML backing the story is as simple as:
a: <input type='text'/><br/>
b: <input type='text'/><br/>
c: <input type='text' id='magic'/><br/>
If you want to play with it, here it is on jsfiddle
NOTE: This still is not the perfect solution, the sentinel is just reset inside the control, so if a tabpress moving the focus does not activate our input, the sentinel stucks, and the first event will be swallowed.. So here is an example of wrong behaviour:
Click on input A
Press TAB (focus moves to input B, tabPressed becomes true)
Click on input C
Press TAB (it is eaten up as sentinel is true)
Press TAB (now it goes through)
Still it is slightly better to have to press TAB twice as to have something happening automatically, wo user control...

the shift key is just ignored after another key has been depressed, poor shift key. How do I detect when it is released?

I have a text input, that presently goes transparent when a user presses shift (keydown) and binds a listener for the shift key going up
ie.
$('#foo').keydown(function(){
if(event.which==16){
//make #foo transparent
$(this).keyup(function(){
if(event.which==16){
//return #foo to its former glory
$(this).unbind('keyup');
}
});
};
})
This works fine when no characters are pressed in the interim between depressing and releasing the shift key. The problem is that when shift is down and another character is pressed, the shift key seems to have been completely forgotten about. When the shift key is released, no keyup fires.
I tried triggering a 'fake' keydown with the .which property set to 16, to nudge it in the right direction after other characters are pressed, but to no avail.
Any suggestions would be greatly appreciated!
While pressing shift, it will continuously trigger keydown events until you release it, so your example will bind as many keyup handlers as there are keydown events triggered. This will most likely cause all kind of weird problems.
Instead, bind both keydown and keyup to the same handler and do your magic in there:
$("#foo").on("keydown keyup", function (e) {
if (e.which === 16) {
if (e.type === "keydown") {
// make #foo transparent
} else {
// return #foo to its former glory
}
}
});
See test case on jsFiddle.
However, if you lose focus of the input while pressing shift and then release, it will not work as expected. One way to solve it is to bind to window instead:
var $foo = $("#foo");
var shiftPressed = false;
$(window).on("keydown keyup", function (e) {
if (e.which === 16) {
shiftPressed = e.type === "keydown";
if (shiftPressed && e.target === $foo[0]) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
}
});
$foo.on("focus blur", function (e) {
if (e.type === "focus" && shiftPressed) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
});
See test case on jsFiddle.

Categories

Resources