event.altKey is not returning anything - javascript

I'am trying to show / hide a div if the Alt button is pressed. I'm listening to a keypress and using event.altKey to determine if alt/option was pressed. But this wasn't working. So I logged the event.
#HostListener( 'document:keypress', [ '$event' ])
handleKeyboardEvent( event: KeyboardEvent ) {
console.log( event.altKey );
}
In the above code if I pressed any number, alphabet or symbol it will print 'false' as expected. But when I press Alt, Ctrl, Shift, Tab nothing happens. It doesn't print true or false.
I also tried printing the keycode. It prints for everything but 'Alt, Ctrl, Shift, Tab'.
What am I doing wrong here?

Keypress doesn't detect some keys, and alt must be one of those keys. I would try using a different event called onkeydown. It can detect more keys. Here's more info on the keydown event: https://developer.mozilla.org/en-US/docs/Web/Events/keydown

you can the following function for alt key function :
function isKeyPressed(event) {
if (event.altKey) {
console.log("The ALT key was pressed!");
} else {
console.log("The ALT key was NOT pressed!");
}
}
and in your html use onkeydown="isKeyPressed(event)" as tag

You can try host property within #Component decorator.
#Component({
...
host: {
'(document:keypress)': 'handleKeyboardEvent($event)'
}
})
export class AppComponent {
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
}
}
Angular recommend using #HostListener decorator over host property
https://angular.io/guide/styleguide#style-06-03

Related

Angular 2 keyboard event triggering safety button

I have an issue with the code below with IE11 triggering the safety button as pictured below
#Component({
selector: 'app-component',
})
class AppComponent {
#HostListener('window:keydown', ['$event'])
doSomething($event) {
// alt + s
if($event.altKey && $event.altKey === 83) {
// perform some action
// saveForm();
// also added this but still triggering in IE11
$event.preventDefault();
}
}
}
I have tried adding $event.preventDefault(), $event.stopPropagation(), $event.cancelBubble = true; and few others.
My problem is it is executing the saveForm(); but also triggering the safety button in IE11. How can i stop the Safety button from opening up in IE?
Using accesskey is the solution.
https://www.w3schools.com/tags/att_accesskey.asp

How to detect Click + [Shift, Ctrl, Alt] in reactjs click event?

I want to do some other things when user Click+[Ctrl], but it seems that I could not detect if user press Ctrl when clicking.
I copy the event object infos below.
bubbles : false
cancelBubble : false
cancelable : false
currentTarget : react
defaultPrevented : false
eventPhase : 2
isTrusted : false
path : Array[1]
returnValue : true
srcElement : react
target : react
timeStamp : 5690056.695
type : "react-click"
I can see the ctrlKey attribute in the arguments[0]-Proxy Object. But this object is unaccessable('Uncaught illegal access'):
[[Target]]
:
SyntheticMouseEvent
_dispatchInstances:ReactDOMComponent
_dispatchListeners:(e)
_targetInst:ReactDOMComponent
altKey:false
bubbles:true
button:0
buttons:0
cancelable:true
clientX:275
clientY:315
ctrlKey:false
Your click handling function would have a format as such:
clickHandler: function (event, value) {
event.stopPropagation();
// In that case, event.ctrlKey does the trick.
if (event.ctrlKey) {
console.debug("Ctrl+click has just happened!");
}
}
you can use this code below in your render() method
document.addEventListener('click', (e) => {
if (e.ctrlKey) {
console.log('With ctrl, do something...');
}
});
In the click event of this element you can check if at the moment of the click, a button (with keycode of ctrl in this case) is pressed down

How to avoid keydown delay with jQuery?

GOAL:
When a user types character in a text box, make a button appear. When the user clears the text box using the backspace key but holds down that key for a few extra seconds, hide the button instantly.
ISSUE:
If a user types in a single character, and uses the backspace to remove it—by holding down the backspace key a few extra seconds—there is a delay before the button is hidden. This only happens when the user typed only one character and then held down the the backspace key without letting go. If instead the user typed multiple characters, and then held down the backspace key until the textbox was empty, there was no delay in hiding the button.
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
$('#tbox').on('keydown keypress keyup',function(){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
JSFIDDLE:
http://jsfiddle.net/odkut0dh/
A little walkthrough the situation :
Assuming that <input> value is "x" and you type backspace :
- When the keydown event fires the input's value is still "x".
- When the keypress fires, it still "x".
If you don't release the key :
__ keydown fires again, after some delay, depending on os I guess value is now "".
__ keypress fires again, value is still "".
__ When you release the key, keyup fires, value is "".
If you do release the key :
__ keypress fires directly, value is "".
The solution For IE10+ is to use the input event which will fire when the textEditable element's content has changed or, as suggested by #Mayhem, the change event, which won't even listen for key inputs and has a better browser support than input
$('#tbox').on('input change',function(e){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
As i've aleady made comments on this one, did a quick google and came across this post which might make it a little easier.. Detect all changes to a <input type="text"> (immediately) using JQuery
So i put it into a fiddle here for you to test: Slight Modded Version
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').each(function() {
var elem = $(this);
elem.data('oldVal', elem.val());
elem.bind("propertychange change click keyup input paste", function(event){
if (elem.data('oldVal') != elem.val()) {
if (elem.val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
elem.data('oldVal', elem.val());
}
});
});
As i dont have to much time to break this code down into sections... By the looks of it.. You dont need the elem.data... Just the bind event...
... ah seems i decided to shorten the code for you...
http://jsfiddle.net/z2ew3fqz/3/
Using the same HTML...
Shortest version i could make from the example given above
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').bind("propertychange change click keyup input paste", function(event){
if ($(this).val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
});
I've quickly tested this on chrome.. mouse/function keys all seem to affect it correctly... Other browsers i'll leave upto the OP to test.. Let me know if any issues in a particular browser..
IE10 seems to be the min support for this .. IE9 might be able to have a js prototype done.. But how important is this for support in your project? to support IE<10?
The Problem is that $('#tbox').val(); is not empty ('') when backspace is pressed. So You have to delay the value check.
When you press down the key, the first thing what happend is that the keydown event is fired, then after that the key action will be performed on the input field.
$('#tbox').on('keydown keypress keyup',function(){
setTimeout(function () {
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
},0);
});
You can prevent repeating keydown by control it on key up by an global variable:
var allow = true;
$(document).on('keydown', function(e) {
if (e.repeat != undefined) {
allow = !e.repeat;
}
if (!allowed) return;
allowed = false;
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
$(document).keyup(function(e) {
allowed = true;
});

jQuery TextExt Plugin: KeyPress

I use TextExt, textext.plugin.tags.js
jQuery("#InputID").textext({ plugins: 'tags' }).keypress(function (event) {
//See if the key pressed is 'enter'
if (event.which == 13) {
alert("pressed key is enter");
});
but after press key enter, alert message not displaying
I want to catch keypress enter and KeyUp, some proposal?
Looking at the tags documentation, it appears that you want to use event enterKeyPress:
http://textextjs.com/manual/textext.html
I don't believe that textExt({plugin: 'tags'}) supports the keypress() method. Try this:
jQuery("#InputID").textext({ plugins: 'tags' }).on({
enterKeyPress: function(event) { alert('enter!'); }
});

jQuery.fn.autoResize and Return Key

I am using the following library:
https://github.com/padolsey/jQuery.fn.autoResize
for changing the dimension of textarea box.
$('textarea').autoResize();
By default the Return key in the textarea generate a new line.
How can I disable the autoResize on the Return key action?
Actually I use the Return key to trigger another action:
$("textarea").keypress(function(event) {
if ( event.which == 13 ) {
alert("Handler for .keypress('enter') called.");
}
});
but at the same time I would like to disable the autoResize just on enter keypress.
I did try the following code, but it does not work:
$("textarea").keypress(function(event) {
if ( event.which == 13 ) {
alert("Handler for .keypress('enter') called.");
event.stopPropagation();
}
});
$('textarea').autoResize({
onBeforeResize: function(event){
console.log('Before');
event.stopPropagation();
}
});
You may also want to try event.stopImmediatePropagation() if the handler for autoResize is attached directly to the textarea.
And given stopImmediatePropagation, you will need to make sure your event handler is registered before the autoResize.

Categories

Resources