I'm currently running into an issue with trying to use the JavaScript event object. I have a Javascript function that waits for an onblur event and check to see if a the shiftkey is being pressed for an element on the document and do something if that's the case. The event.shiftKey works perfectly in IE 9 to detect if the shift key is pressed, but for the event object is different for an onblur event in IE 11 and it doesn't support the shiftKey event. When I did an alert on the event object, it says it was '[ojbect msEventObj]' in IE 9 and '[object focusEvent]' in IE 11. Is there a way to get around this difference between IE 9 and IE 11?
Here's the JavaScript code:
//using alert(event.shiftkey) gives me undefined in IE 11 because event
//is focusEvent object not msEventObj for some reason
element.onblur = function (){
if (event.shiftKey == false) {
alert('shift key was not pressed!');
}
}
The problem is that event.shiftKey is not accessible from onblur - and you weren't passing the event to your event handler - I think you're trying to target onkeypress:
element.onkeypress = function (ex) { //pass event to handler ('ex' in this example)
alert(ex.shiftKey);
}
This returns true when the shift key is being held down - false when it is not.
you didn't define event, should be like this:
element.onblur = function (event){
if (event.shiftKey == false) {
alert('shift key was not pressed!');
}
}
I came across a similar problem for tab navigation.
element.addEventListener('keydown', (event) => {
if (event.keyCode !== 9) return;
if (!event.shiftKey) {
event.preventDefault();
YOURTARGET.focus();
}
});
Instead of a blur event, I listen for a keydown, check if it's tab, then run the code I want. It gives me access to event.shiftKey.
I have 2 events; one for when i click a button and the other for when i press my down arrow.
They are both reffering to the same method. My code for that looks like this:
$('.button').on('click', function() {
someMethod();
});
$(document).keydown(function(e) {
if (e.keyCode === 40) {
someMethod();
return false;
}
});
Is there a better or shorter way to do this? Also when i want to add another event to it?
Make your method as you required
pass "e" for KeyDown and not pass "e" for click and then check e in your function
if(typeof e != "undefined" && e.keyCode === 40)
I hope you get it
You can shorten the first one by passing the handler reference instead of calling it through anonymous function.
$('.button').on('click', someMethod);
I am writing a Greasemonkey script. I want to trigger a certain code to run when the user presses the "Q" key. I did a little bit of research, and most of the sources I saw suggested using window.onkeypress.
To test this method, I created a userscript set to run when the users presses Q. Here is my code:
window.onkeypress = function(event) {
if (event.keyCode == 81) {
alert("This is a test.")
}
}
However, upon pressing the Q key, nothing happened. I am wondering if anyone knows why this may be and what I can do to correct it.
In addition, if anyone knows of any other methods I can use to achieve the same effect, it would be greatly appreciated.
keypress events don’t receive a keyCode; try handling keydown instead.
window.onkeydown = function(event) {
if (event.keyCode === 81) {
alert("This is a test.");
}
};
I have started using Dojo's new on module to add my events. It works fine, but now I've run into a problem. When using keypress event I can't seem to get the character value (for example "2" or "b") from the pressed key. Previously I've used the behaviormodule, and the connect module, and then I have been able to get it by using e.keyChar or e.charOrCode, but now they´re undefined.
I have an event set up like this:
on(element, 'keypress', function(e)
{
console.log(e.keyCode); //works, but not what I need
console.log(e.charOrCode); //undefined
console.log(e.keyChar); //undefined
});
How do I get the character of a pressed key when using this module?
In this case, I think what you want is to use e.keyCode in conjunction with the JS-native String.fromCharCode() in order to get the desired character value.
on(element, 'keypress', function(e) {
var character = String.fromCharCode(e.keyCode);
if (character === 'a') { // do a stuff } else { // do something else }
}
Following is my JavaScript (mootools) code:
$('orderNowForm').addEvent('submit', function (event) {
event.preventDefault();
allFilled = false;
$$(".required").each(function (inp) {
if (inp.getValue() != '') {
allFilled = true;
}
});
if (!allFilled) {
$$(".errormsg").setStyle('display', '');
return;
} else {
$$('.defaultText').each(function (input) {
if (input.getValue() == input.getAttribute('title')) {
input.setAttribute('value', '');
}
});
}
this.send({
onSuccess: function () {
$('page_1_table').setStyle('display', 'none');
$('page_2_table').setStyle('display', 'none');
$('page_3_table').setStyle('display', '');
}
});
});
In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the event object does not have a preventDefault method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).
Any Help?
in IE, you can use
event.returnValue = false;
to achieve the same result.
And in order not to get an error, you can test for the existence of preventDefault:
if(event.preventDefault) event.preventDefault();
You can combine the two with:
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.
Try out this fiddle to see the difference in event binding.
http://jsfiddle.net/pFqrY/8/
// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
alert(typeof(event.preventDefault));
});
// preventDefault missing in IE
<button
id="htmlbutton"
onclick="alert(typeof(event.preventDefault));">
button</button>
For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.
e = $.event.fix(e);
After that e.preventDefault(); works fine.
I know this is quite an old post but I just spent some time trying to make this work in IE8.
It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.
Let's say that we have this code:
$('a').on('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.
Even if I set returnValue property directly to false:
$('a').on('click', function(event) {
event.returnValue = false;
event.preventDefault();
});
This also won't work, because I just set some property of jQuery custom event object.
Only solution that works for me is to set property returnValue of global variable event like this:
$('a').on('click', function(event) {
if (window.event) {
window.event.returnValue = false;
}
event.preventDefault();
});
Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.
UPDATE:
As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
Tested on IE 9 and Chrome.
To disable a keyboard key after IE9, use : e.preventDefault();
To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;
If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :
try {
e.keyCode = 0;
}catch (e) {}
Here is a full example for IE7/8 only :
document.attachEvent("onkeydown", function () {
var e = window.event;
//Ctrl+F or F3
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
//Prevent for Ctrl+...
try {
e.keyCode = 0;
}catch (e) {}
//prevent default (could also use e.returnValue = false;)
return false;
}
});
Reference : How to disable keyboard shortcuts in IE7 / IE8
Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build. Let me know your results with it. Everything executes fine on this end in Safari, FF, Opera on OSX. It is exclusively for fixing a problematic IE8 bug, and may have unintended results:
function ie8SafePreventEvent(e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.stop()
};
e.returnValue = false;
e.stopPropagation();
}
Usage:
$('a').click(function (e) {
// Execute code here
ie8SafePreventEvent(e);
return false;
})
preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.
return false in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
I was helped by a method with a function check. This method works in IE8
if(typeof e.preventDefault == 'function'){
e.preventDefault();
} else {
e.returnValue = false;
}