The following snippet works great in chrome/edge/safari. In Firefox the textarea gets focused, but the pressed character isn't being added to the textarea - the first character will be always missing.
document.addEventListener('keypress', (event) => {
document.querySelector('#input').focus();
});
<textarea id="input"></textarea>
How can I make this behave consistently across all browsers?
Here's how you can make it work without browser sniffing: When the keypress happens, bind a handler to the input event on the textarea, and also set a 0-ms timeout.
If the browser accepted the pressed key for the textarea, the input handler will run before the timeout (because the input event fires synchronously). If that happens, you know the browser has handled the keypress correctly, and you can cancel the timeout.
Then, if the timeout fires, you know that the input event hasn't fired and thus the character hasn't been added to the textarea, and you do it programmatically.
In both the event handler and the timeout handler, you unbind the event handler – it should run at most once (per key press).
var textarea = document.getElementById("input");
document.addEventListener("keypress", function (event) {
if (event.target === textarea) {
return;
}
var eventHandler = function () {
textarea.removeEventListener("input", eventHandler);
clearTimeout(timeoutId);
console.log("input event");
}
var timeoutHandler = function () {
var character = ("char" in event) ? event.char : String.fromCharCode(event.charCode);
textarea.value += character;
textarea.removeEventListener("input", eventHandler);
console.log("timeout fired");
}
timeoutId = setTimeout(timeoutHandler, 1);
textarea.addEventListener("input", eventHandler);
textarea.focus();
});
<textarea id="input"></textarea>
<p style="background: #ccc">
<b>Click here</b> to make sure the document is focused, but the textarea is not. Then press a key.
</p>
If you try the above snippet in Firefox, the console will say "timeout fired". In all other browsers it will say "input event". In either case, your pressed key is added to the textarea.
Some notes:
Technically, for consistent behavior you'd need to do more than just append the character to the end; you'd also have to look at things like cursor position and text selection. This may be overkill however.
If you need to support really old browsers, you might want to do a feature check for availability of the input event.
If you have other code that relies on the textarea changing synchronously upon keypress, you'll probably have to make updates there.
While this code will not work if any other browsers share the same behavior as Firefox, the following code will add any key input, given that it is a character whose string length is 1, when the code is run on Firefox:
var mozFocused = false;
document.addEventListener('keypress', (event) => {
document.querySelector('#input').focus();
var isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox && !mozFocused && event.key.length === 1) {
mozFocused = true;
document.querySelector('#input').value += event.key;
}
});
document.querySelector('#input').addEventListener('blur', (event) => {
mozFocused = false;
});
<textarea id="input"></textarea>
Again, note that this does not guarantee it to work across all browsers, as this was a fix for Firefox specifically, but, if you see the same behavior occurring in other browsers, I used the answer from this SO post to detect the current browser the client is using (assuming it is in the list of the browsers that this post discusses): How to detect Safari, Chrome, IE, Firefox and Opera browser?
Related
I have a textarea with keyDown listener
<textarea onKeyDown={handleKeyDown}></textarea>
And the handleKeyDown function:
const handleKeyDown = event => event.preventDefault()
When I typing from windows PC, Chrome Version 90.0.4430.212 (Official Build) (64-bit) everything works perfect: text is not appearing in textarea.
When I typing from mac, chrome 90 everything works perfect too.
But when I grab my Android Phone (Samsung, Android 11), open Mobile Chrome (90.0.4430.210) and start typing, text IS appearing in textarea. And the worst thing is that the only mention about this bug I found is this question, which will be referenced by bots when marking my question as duplicate. There is no answer: maxlength attribute not working anymore.
This is the list of things I tried to prevent mobile chrome from input:
Maxlength = 0 (no effect at all)
readOnly (=disabled, I need focus and selection)
blocking onKeyUp, onKeyPress, onPaste, onCut, onInput
I also tried to manually set value of textarea to '' but if I set a listener which does this, my textarea become completely broken: each time I press key on keyboard, it duplicates all previous content.
My question is how to prevent input, maybe there is a hack or trick? Please don't send me to android report forums where this bug may be discussed or another questions...
I would first check to see if the events are working when adding eventlisteners. There must be a way to handle key events on Android:
<textarea id="mytextarea"></textarea>
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('keydown', (event) => {
console.log(event.code);
});
If this is not working; you asked for a hack or trick: try the focus and blur events, then you could run a function on interval that clears the textarea. Note that this blocking trick is something that goes against good user experience conventions, so should be considered a hack/trick for sure ;-)
<textarea id="mytextarea"></textarea>
let int1;
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('focus', () => {
clearInterval(int1);
int1 = setInterval(() => {
mytextarea.value = '';
}, 10)
});
mytextarea.addEventListener('blur', () => {
clearInterval(int1);
});
Instead of using event.key or event.code properties of keypress (keyup, keydown) event, I have used event.inputType, event.data of update event and added few restricting attributes to the input tag to overcome 'smartness' of mobile keyboard app. It is an ugly hack but worked for my purpose.
HTML:
<textarea id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" ></textarea>
</div>
JS:
var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);
function do_on_input(e) {
if( e.inputType == "insertText"){
console.log( e.data );
}
if( e.inputType == "deleteContentBackward"){
console.log('Backspace');
}
if( e.inputType == "insertCompositionText"){
// without restrictive attribbutes you will need to deal with this type events
}
}
I am facing a problem with IE not Chrome. It does not trigger change event after I change the value by javascript. I think it work right as the specification of event change. When user change the input by javascript then lose focus on the input that means user does not(javascript does) change the input. But Chrome is smart guy he knows user did saw the change on input so he trigger change :). Is there anyway to make IE behaves like Chrome?
document.getElementById('inputName').addEventListener("keyup", function(e){
this.value += '_';
});
<body>
<input id="inputName" value="name" onchange="document.getElementById('outputName').innerHTML = document.getElementById('inputName').value"/>
<div id="outputName">name</div>
</body>
It indeed seems weird that the change event gets overriden by this js action... I guess specs are relatively unclear on this point, so I'm not sure if we can call it a bug.
Anyway, you can mimick this behavior yourself by listening to the input event, which will trigger every time the user did commit changes to the input's value.
From there, you just need to raise a flag that you will read in the blur event:
inp.oninput = function(e) { // every time the user commits a change
this._hasChanged = true; // raise a flag
};
inp.onblur = function(e) { // when we loose focus
if (this._hasChanged && // only if there were some changes made by the user
typeof this._onchange === 'function') {
this._onchange(); // trigger our fake change event
}
this._hasChanged = false; // set the flag back to false
};
inp._onchange = function(e) { // our fake onchange listener
log.textContent = this.value;
};
inp.onkeyup = function(e) {
this.value += '_';
}
<input id="inp" value="name">
<pre id="log"></pre>
Solution:
https://jsfiddle.net/hrr3n0eh/
I am trying to create a Drop down list, that when a user holds the SHIFT key, it will select the same index on all other drop down lists.
Currently, I am doing the following:
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey });
$(document).on('change', '.report_info select', function (e) {
if (shifted) {
//Code to change other drop down lists.
}
});
This only works if you press and hold the shift key before you enter the drop down list. If you are inside the DDL and press the shift key, the keyup/keydown event will not fire and shifted will remain false
Is there any way to catch the keyup/keydown event while a dropdownlist is focused?
Edit:
Looks like it might be an issue with Chrome only, Just tried adding the following, and it works in Firefox and IE, but not Chrome:
$(document).on('keyup keydown', 'select', function (e) {
shifted = e.shiftKey;
});
Here is a fiddle of it not working in chrome: http://jsfiddle.net/ue6xqm1q/4
I think #judgeja's response may be your best bet. I'm posting this as an "answer" instead of a comment, because I've done my own research to determine that absolutely no event gets fired when a select element is open in Chrome.
See Fiddle: http://jsfiddle.net/m4tndtu4/6/
I've attached all possible event handlers (I think) to the input element and both select elements.
In Chrome, you'll see many events fire when working with the input element, but you'll see no events fire when working in the first select element when it is open.
Interestingly, events do fire in Chrome if the select element has the multiple attribute or size>1.
In Firefox, you'll see events firing on all three elements.
Outside #judgeja's suggestion, your best bet may be to simulate the select element.
UPDATE
Warning: Chrome (mis)behavior differs on different platforms! In Chrome Windows a keydown event is triggered right after the select is released, while on OsX it is not. This explains why #judgeja solution worked for some, and didn't for me, while mine worked on OsX and not on Windows.
So I created an updated fiddle to merge my OsX solution with his Windows one.
http://jsfiddle.net/0fz5vcq6/5/
On platforms where the keydown is triggered uses #judgeja solution, if it is not triggered it tests for a keyup event without the previous keydown (my previous solution). It is ugly as it works only after RELEASE of the shift key, but ugly only on Chrome OsX.
var shifted = false;
var hackytimer = 0;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
if(Date.now() - hackytimer <200){
alert("you pressed shift inside the select (Win)");
changeAllSelects($(this).val());
} shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16) {
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select (OsX)");
$('.report_info select').each(function () {
changeAllSelects(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
hackytimer = Date.now();
if (shifted) {
changeAllSelects($(this).val());
} else {
lastval=$(this).val();
}
});
function changeAllSelects(cr){
hackytimer = 0;
$('.report_info select').each(function () {
$(this).val(cr);
});
}
Credit goes mainly to #judgeja for his timer solution with some added workaround for the Mac (and other platforms that behave the same)
I still think emulating the selects with something HTML like http://gregfranko.com/jquery.selectBoxIt.js/ is cleaner as they should not interfere with keydown/keyups.
PREVIOUS SOLUTION (OsX only)
The only solution I could think of, in the total absence of any event, is to test if a shift up occurred without the previous shift down. This may work if you don't have other elements that behave the same way as the selects
http://jsfiddle.net/6jkkgx5e/
It is a bit tricky and dirty, will work AFTER the user releases the shift key
var shifted = false;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16){
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select");
$('.report_info select').each(function () {
$(this).val(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info select').each(function () {
$(this).val(cr);
});
} else {
lastval=cr;
}
});
Should behave normally on non buggy browsers. Anyway I agree emulating the selects with something HTML like http://gregfranko.com/jquery.selectBoxIt.js/ might be the cleaner way.
Your syntax looks incorrect.
$("#target").keydown(function() {
alert( "Handler for .keydown() called." );
});
This is a pretty hacky solution to be honest, but it's a means to an ends until you hopefully find something better.
Since the problem is chrome doesn't register the keydown/keyup events on the select elements until after the dropdownlist has disappeared, we need to either
a) figure out how to make the event fire (I've no idea)
or
b) check if our conditions were met in a different order.
Chrome will fire the shift keypress event after click, so we can simply check if click was pressed immediately before this event. Since other browsers behave more expectedly we'll also leave the previous code in place.
To do this we set a timer on the click event, and then when the shift event for the select is fired, if the click event timer was also just set we should run our code here so that chrome will fire it. We reset the timer then so that it isn't fired multiple times.
NOTE: if you press shift immediately after setting the values (within whatever limit from the click you specify), it will also set them all. I don't think this is unreasonable as it actually feels quite natural when it happens.
I used the following code:
var shifted = false;
var hackytimer = 0;
$(document).on('keyup keydown', function (e) {
shifted = e.shiftKey;
});
$(document).on('keyup keydown', 'select', function (e) {
shifted = e.shiftKey;
if(Date.now() - hackytimer <200){
changeAllSelects($(this).val());
}
});
$(document).on('change', '.report_info select', function (e) {
hackytimer = Date.now();
if (shifted) {
changeAllSelects($(this).val());
}
});
function changeAllSelects(cr){
hackytimer = 0;
$('.report_info select').each(function () {
$(this).val(cr);
});
}
See working example here: http://jsfiddle.net/0fz5vcq6/2/
First of all. You should pick an event to register. Don't register to keyup and keydown the same time. You give the browser a hard time, because they affect your end result. To see what I mean, just edit the plunk, add a keyup event. The end result behaves a little sloppy.
keyup: Event fired when a key is released on the keyboard.
keydown: Event fired when a key is pressed on the keyboard.
keypress: Event fired when a key is pressed on the keyboard.
They have their differences, better stick to one, I prefer for this example to use keydown, just plays better with me, you can use keyup.
Edit: A quick note. The keyup for my example doesn't play well, because it seems, change in the selectedIndex, comes first and then the binded event. On keydown, first the event fires, does it's work and then the selectedIndex changes. To play with keyup, the code below needs some modification, that means the step is not needed, when you use keyup
I have a plnkr demo here.
I've tested it on IE10, Opera, Safari, Firefox and Chrome. As you might expect, webkit browsers, don't fire the keydown/keyup/keypress event when a select list has focus. Reason unknown for me, at the moment. In Firefox works great. On IE works partially. So, in order to achieve your goal, custom code to the rescue! I just binded a change event to the document, i hear for kewdown and change. If the event type is change, then the workaround comes into play. Here some code:
$(document).ready(function(){
$(document).on('keydown change', 'select', function(evt){
var shiftKey = evt.shiftKey;
var code = evt.keyCode || evt.which;
//if it's a change event and i dont have any shiftKey or code
//set the to a default value of true
if(evt.type === 'change' && !shiftKey && !code){
//special! only when change is fired
shiftKey = true;
code = true;
}
//if shift key
if(shiftKey && (code === 40 || code === 38 || code === true)){
var target = $(evt.target);
//if code is not true means it is not a change event, go ahead and set
//a step value, else no step value
var step = (code !== true) ? (code === 40) ? 1 : -1 : 0;
var index = target[0].selectedIndex + step;
//just to keep the lower and upper bound of the select list
if(index < 0){
index = 0;
}else if(index >= target[0].length){
index = target[0].length - 1;
}
//get all other select lists
var allOtherSelects = target.closest('div').siblings('div').children('select');
//foreach select list, set its selectedIndex
$.each(allOtherSelects, function(i, el){
el.selectedIndex = index;
});
}
});
});
Chrome hack: You can set custom event for document. And firing this event when press the shift key inside the DDL. Jquery firing trigger can pass custom params.
Check the working JS FIDDLER
Try the following script for your scenario
<script type="text/javascript" language="javascript">
window.shifted = false;
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey; });
$(document).on('change', 'select.report_info', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info').each(function () {
$(this).val(cr);
});
}
});
</script>
Bryan,
you can try the following way to do this. I tested on Jsfiddle it working in your way If I got your question correctly.
var shifted = false;
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey; });
$("select").on('keyup keydown', function (e) {
shifted = e.shiftKey;
});
$('.report_info select').on('change', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info select').each(function () {
$(this).val(cr);
});
}
});
Please let me know if it works for you.
Hello that was not working because of no focus on your select which has keydown bound
try this
http://jsfiddle.net/t8fsuy33/
$('select').first().focus();
Hop this thing help you out.. :)
var onkeydown = (function (ev) {
var key;
var isShift;
if (window.event) {
key = window.event.keyCode;
isShift = window.event.shiftKey ? true : false;
} else {
key = ev.which;
isShift = ev.shiftKey ? true : false;
}
if ( isShift ) {
switch (key) {
case 16: // ignore shift key
break;
default:
alert(key);
// do stuff here?
break;
}
}
});
I found a very unique solution to this issue specifically for Chrome. It appears Chrome shifts outside the normal dom for select elements when they have focus so you never get the onkey(down|press|up) events to capture the keycode. However if the size of the select box is >1 then it works. But anyone who wants an actual drop down box instead of what looks like a combo box can solve this issue with this code. In my case I was trying to prevent the backspace key from going back to the previous browser page.
Javascript looks like this:
$(document).ready(function() {
$('select').keypress(function(event)
{ return cancelBackspace(event) });
$('select').keydown(function(event)
{ return cancelBackspace(event) });
});
function cancelBackspace(event) {
if (event.keyCode == 8) {
return false;
}
}
Then HTML looks like this:
<select id="coaacct" style="border:none;width:295px;" onclick="if (this.size){this.size=''}else{this.size='20'};">
I use the onclick event to change the size of the select box to 20 if it has no size and change it back to nothing if it has a size. This way it functions like a normal select dropdown but because it has a size greater than 1 when you are selecting the option it will detect keycodes. I didn't see this answered adequately anywhere else so I thought I would share my solution.
If you need to do things with a dropdown that are this granular, it's likely not worth it to use the native <select> element as-is. In this thread alone, numerous implementation differences are discussed, and there are plenty more that are outside the scope of this discussion but will also likely affect you. There are several JS libraries that can wrap this control, leaving it as-is on mobile (where the native control is actually needed) but emulating it on desktop, where the control doesn't really do much that can't be emulated in JS.
bootstrap - doesn't automatically wrap native control for mobile
dropdown.js
dropdown.dot.js
How do I detect change event on textarea using javascript?
I'm trying to detect how many characters left is available as you type.
I tried using the onchange event, but that seems to only kick in when focus is out.
The best way to do this, cross-browser: use a combination of the input and onpropertychange events, like so:
var area = container.querySelector('textarea');
if (area.addEventListener) {
area.addEventListener('input', function() {
// event handling code for sane browsers
}, false);
} else if (area.attachEvent) {
area.attachEvent('onpropertychange', function() {
// IE-specific event handling code
});
}
The input event takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychange takes care of IE8 (it also works with IE6 and 7, but there are some bugs).
The advantage of using input and onpropertychange is that they don't fire unnecessarily (like when pressing the Ctrl or Shift keys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.
Now IE, as always, does a half-assed job of supporting this: neither input nor onpropertychange fires in IE when characters are deleted from the textarea. So if you need to handle deletion of characters in IE, use keypress (as opposed to using keyup / keydown, because they fire only once even if the user presses and holds a key down).
Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
EDIT: It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListener property on the textarea does not imply you're working with a sane browser; similarly the presence of the attachEvent property does not imply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's comment for pointers.
You will need to use onkeyup and onchange for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
See my answer on How to impose maxlength on textArea for a code sample.
For Google-Chrome, oninput will be sufficient (Tested on Windows 7 with Version 22.0.1229.94 m).
For IE 9, oninput will catch everything except cut via contextmenu and backspace.
For IE 8, onpropertychange is required to catch pasting in addition to oninput.
For IE 9 + 8, onkeyup is required to catch backspace.
For IE 9 + 8, onmousemove is the only way I found to catch cutting via contextmenu
Not tested on Firefox.
var isIE = /*#cc_on!#*/false; // Note: This line breaks closure compiler...
function SuperDuperFunction() {
// DoSomething
}
function SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally() {
if(isIE) // For Chrome, oninput works as expected
SuperDuperFunction();
}
<textarea id="taSource"
class="taSplitted"
rows="4"
cols="50"
oninput="SuperDuperFunction();"
onpropertychange="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onmousemove="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onkeyup="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();">
Test
</textarea>
I know this isn't exactly your question but I thought this might be useful.
For certain applications it is nice to have the change function fire not every single time a key is pressed. This can be achieved with something like this:
var text = document.createElement('textarea');
text.rows = 10;
text.cols = 40;
document.body.appendChild(text);
text.onkeyup = function(){
var callcount = 0;
var action = function(){
alert('changed');
}
var delayAction = function(action, time){
var expectcallcount = callcount;
var delay = function(){
if(callcount == expectcallcount){
action();
}
}
setTimeout(delay, time);
}
return function(eventtrigger){
++callcount;
delayAction(action, 1200);
}
}();
This works by testing if a more recent event has fired within a certain delay period. Good luck!
I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.
$('div.lawyerList').on('change','textarea',function(){
// Change occurred so count chars...
});
or
$('textarea').on('change',function(){
// Change occurred so count chars...
});
You can listen to event on change of textarea and do the changes as per you want. Here is one example.
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
var textLn = textArea.value.length;
if(textLn >= 100) {
textArea.style.fontSize = '10pt';
}
})
<html>
<textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
</textarea>
</html>
Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.
<input type="text" pattern="[a-zA-Z]+" id="my-input">
var myInput = document.getElementById = "my-input";
myInput.addEventListener("keyup", function(){
if(!this.checkValidity() || !this.value){
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
});
Code I have used for IE 11 without jquery and just for a single textarea:
Javascript:
// Impede que o comentário tenha mais de num_max caracteres
var internalChange= 0; // important, prevent reenter
function limit_char(max)
{
if (internalChange == 1)
{
internalChange= 0;
return;
}
internalChange= 1;
// <form> and <textarea> are the ID's of your form and textarea objects
<form>.<textarea>.value= <form>.<textarea>.value.substring(0,max);
}
and html:
<TEXTAREA onpropertychange='limit_char(5)' ...
Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.
<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea>
<div><span id="spn"></span> characters left</div>
function check(){
var string = document.getElementById("url").value
var left = 15 - string.length;
document.getElementById("spn").innerHTML = left;
}
The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.
self.setInterval('checkTextAreaValue()', 50);
EDIT: After waited a while and didn't get anything yet, I've decided
to do shortcut disable thingy only for
IE now. Is there a possibility to disable
IE shortcut keys to access menus/print
etc. via vbscript?
Is it possible to disable browser shortkeys?
Because many of them are using in application. For instance, Ctrl+p is using and I don't want browser to popup the print window.
Yes, you can listen for the various key combinations with javascript and disable the default behaviors. There's even a library that you can use and test here. I just tested it using google chrome and firefox in their demo textarea, and it works as you want.
shortcut.add("Ctrl+P",function() {
return;
});
This works in the browsers that I listed above, but IE will not allow you to override the default behavior in some cases.
Your only option in IE is to disable the Ctrl key entirely with something like:
document.onkeydown = function () {
if (event.keyCode == 17) alert('Ctrl Key is disabled');
};
Which is not ideal and probably not what you want, but it will work.
You can try creating an event handler for keydown event, check on the keyCode and prevent its default action if needed. However this will not work in all browsers.
An example for Firefox (canceling "Print" short key, verified):
document.addEventListener("keydown", function(oEvent) {
if (oEvent.keyCode == 80 && oEvent.ctrlKey)
oEvent.preventDefault();
}, false)
There is a nice trick to fight with IE10+, to avoid display browser menus on alt key combinations, like Alt + F, Alt + H ...
I recently used on IE11, just add an anchor with the attribute accesskey:[yourKey] on your body
<body>
<script type="text/javascript">
window.onkeydown = function(e){
console.log(e.keyCode + " alt: " + e.altKey);
e.preventDefault();
};
window.onkeyup = function(e){
console.log(e.keyCode + " alt: " + e.altKey);
e.preventDefault();
};
</script>
</body>
Now when you press Alt + f the browser will not display "File popup" as usual, and will let events keydown and keyup gets to you, and not only keydown.
I am working on similar problem, hooking keyboard event Below code works well to disable, except the flash object on the IE has not got the focus. Since I am trying to handle keyboard event on the flash object, this code does not work for me.
function hookKeyboardEvents(e) {
// get key code
var key_code = (window.event) ? event.keyCode : e.which;
// case :if it is IE event
if (window.event)
{
if (!event.shiftKey && !event.ctrlKey) {
window.event.returnValue = null;
event.keyCode = 0;
}
}
// case: if it is firefox event
else
e.preventDefault();
}
window.document.onkeydown = hookKeyboardEvents;
From you application after calling the method on Ctrl+P just make the keycode as zero.I think that will solve your problem...
window.event.keyCode=0;
this will set the keycode as zero..So when explorer checks for the keyCode it will be zero...so default function will not execute...
Try this...just a suggestion
This works for me in IE 8. The important part is IE requires ev.returnValue to be set to false. NOTE: this only works if you have focus on some element on the document...that is, if you just load the page and hit 'ctrl-p' you'll see the print dialog. But if you click somewhere on the page, then try it, it should suppress the print dialog.
document.onkeydown = function (e) {
var ev = e||window.event;
// Do what I want keys to do ...
// Block browser short cuts
if(ev.preventDefault) // non-IE browsers
ev.preventDefault();
else // IE Only
ev.returnValue = false;
};