How to register document.onkeypress event - javascript

I want to register keypress events for a document using javascript.
I have used:
document.attachEvent("onkeydown", my_onkeydown_handler);
It works fine with IE,
but not with Firefox and Chrome.
I also tried:
document.addEventListener("onkeydown", my_onkeydown_handler, true);
// (with false value also)
But it still doesn't work with Firefox and Chrome.
Is there a solution, am I missing something?

You are looking for:
EDIT:
Javascript:
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("You hit the enter key.");
} else {
alert("Oh no you didn't.");
}
}
DEMO: JSFIDDLE

You are probably looking for:
document.body.addEventListener('keydown', function (e) {
alert('hello world');
});​​​​​​​
But it is almost certainly going to be worth your time to use an existing library to abstract over the problems of the many browsers out there.

Please go through following links for detailed description.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener
http://www.reloco.com.ar/mozilla/compat.html
In short, write handler as
function myFunction(e)
{
///For IE
if(!e)
e=window.event;
// use e as event in rest of code.
}

Related

preventDefault() like functionality in javascript

I have already gone through this question
event.preventDefault() vs. return false
But didn't find my solution. Actually i am using javascript function to go back to previous page that is working fine on click of
<img src="images/backbtn.png">
function
function goBack(){
window.history.back();
}
When i click on <a> it includes # in url which i want to prevent. In jquery we use preventDefault() to stop the default event of an element but is there any similar function in javascript to stop it.
I know i can use javascript:void(0) in href which will solve the problem but there can be many other instances so i want to know about function in javascript.
I tried using return false; but it i write this on top like this
function goBack(){
return false;
window.history.back();
}
Then it stops the function to execute and if i write like this
function goBack(){
window.history.back();
return false;
}
Then no effect from this return false;. I am sure there is some in javascript as jquery is generated from javascript.
Any help would be appreciated. Thanks in advance!
As far as I know, preventDefault() also is a native JS function, so you can use it without jQuery and get same result.
You can read more about it here: MDN: Event.preventDefault()
event.preventDefault() works both in Javasccript and Jquery
If getting the # is the problem and for some reason you really want to use only preventDefault() then you must pass the event into the function and then inside the function use event.preventDefault()
<img src="images/backbtn.png">
Then in your Javascript use this passed event and stop the default behaviour.
function goBack(event){
event.preventDefault();
window.history.back();
}
To add to the answers, return false in jquery does both event.preventDefault and event.stopPropagation()
From jquery source code, jquery.event.dispatch
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
Both preventDefault and stopPropagation are available in Javascript.
For IE < 9, event.stopPropagation can be done by event.cancelBubble = true
and event.preventDefault can be done by event.returnValue = false
preventDefault exists in javascript, but if you are interested in a jQuery like solution you need to take care of compatibility issues.
A different solution, considering the compatibility issues with old browsers, is:
function goBack(evt){
var e = evt || window.event;
if (e !== undefined) {
if (e.preventDefault) {
e.preventDefault();
} else { // IE
e.returnValue = false;
}
}
window.history.back();
}
<img src="images/backbtn.png">

Triggering an alert with a keypress

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

Managing JavaScript hotkeys in Chrome Browser

I have the following jQuery code on a site I built:
$(document).ready(function() {
// Other Bindings/Initializations Removed
// Hotkey Event Handler to 'doSomething'
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
$(document).keypress("a",function(e) {
if(e.altKey) { // Doesn't work
doSomething();
}
});
// Hotkey Event Handler to 'doSomething'
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
$(document).keypress("a",function(e) {
if(e.shiftKey) { //Works as Expected?
doSomething();
}
});
});
The code catches key-press combination events, in this case "Alt-A", and then proceeds to call a function which preforms the appropriate action. I tested this feature in FireFox and the function was called as expected. When I tested the feature in Chrome the function was not called and an obnoxious error tone was emitted instead. I thought that perhaps "Alt-A" collided with an important browser hotkey combination so changed "A" to "N", "G", and then "K"; each time the function was not called and the error tone was emitted. However when I created a Shift-A/N/G/K hotkey combination, Chrome called the function as expected.
Why does Chrome handle the "Alt" key differently?
How to I define a hotkey for my site so that it will work in Chrome using the "Alt" key?
This works in Chrome and Firefox, however in IE Alt+a opens the favorites menu. I'm not sure how you would override that.
Fiddle
HTML:
<a accesskey="a">​
Javascript:
$(document).ready(function() {
// Other Bindings/Initializations Removed
// Hotkey Event Handler to 'doSomething'
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
$(document).keypress("a", function(e) {
if (e.shiftKey) { //Works as Expected?
alert("shift a");
}
if (e.altKey) {
alt_a_function();
}
});
$(document).on("click", "[accesskey=a]", function() {
alt_a_function();
});
});
function alt_a_function() {
alert("alt a");
}​
The jQuery docs say that the first argument to .keypress() is "A map of data that will be passed to the event handler." Perhaps jQuery is confused when that object is a string, which causes an error in Chrome.
To check for a particular key in the event handler, use e.which to get the character code instead.

Is there a 'has focus' in JavaScript (or jQuery)?

Is there something I can do like this (perhap via a plugin)
if ( ! $('form#contact input]').hasFocus()) {
$('form#contact input:first]').focus();
}
Basically, set focus to the first input, but only if the user has not already clicked into anything?
I know this will work too, but is there anything more elegant?
$(function() {
var focused = false;
$('form#contact input]').focus(function() {
focused = true;
});
setTimeout(function() {
if ( ! focused) {
$('form#contact input:first]').focus();
}
}, 500);
});
There is no native solution but yes there is a more elegant way you can do it:
jQuery.extend(jQuery.expr[':'], {
focus: "a == document.activeElement"
});
You're defining a new selector. See Plugins/Authoring. Then you can do:
if ($("...").is(":focus")) {
...
}
or:
$("input:focus").doStuff();
$('input:focus')
It's CSS. You don't need to create a "custom selector." It already exists! http://www.w3schools.com/CSS/pr_pseudo_focus.asp
Just attach whatever process you want to do to that selector, and it will weed it out if the element in question is not focused. I did this recently to keep a keyup from instantiating an email input error check when the e-mail input wasn't being used.
If all you're trying to do is check if the user has focused on anything themselves, just do this:
if($('input:focus').size() == 0){
/* Perform your function! */
}
jQuery 1.6 now has a dedicated :focus selector.
I had trouble with cletus approach, using jQuery 1.3.2 and Firefox 3.6.8, because the string "a == document.activeElement" was not a valid function.
I fixed it defining a function for the focus key. In fact, all other keys defined in jQuery.expr[':'] are defined as functions. Here's the code:
jQuery.extend(jQuery.expr[':'], {
focus: function(e){ return e == document.activeElement; }
});
So, now it works as expected.
However, I was experiencing some strange behaviour in Firefox 3.6.8 (maybe a bug in FF?). If I clicked on an input text while the page was rendering, and if I called is(":focus") on page load, I would get an error from the browser, reported by FireBug, and the script would break.
To solve this, I surrounded the code with a try...catch block, returning false on error. Use it if you want to prevent your users from experiencing the same error:
jQuery.extend(jQuery.expr[':'], {
focus: function(e){
try{ return e == document.activeElement; }
catch(err){ return false; }
}
});
Frustratingly difficult to find a solution to this problem considering the solution is actually very simple:
if (document.activeElement == this) {
// has focus
}
if (document.activeElement != this) {
// does not have focus
}
No, there isn't.
However, you can simulate it like this:
$(':input')
.data('focused', false)
.focus(function() { $.data(this, 'focused', true); })
.blur(function() { $.data(this, 'focused', false); });
There is a plugin http://plugins.jquery.com/project/focused
Also you can check Using jQuery to test if an input has focus
Here is a succinct way to do it.
$(document.activeElement)
or to plug it into your example..
if ($('form#contact input]')[0]!=$(document.activeElement)) { ... }
I know this is an old question, but may be my solution will help someone :)
since this didnt worked for me:
if ($(this)!=$(document.activeElement)) { ... }
..were "this" is returned from blur function. So i did this:
if ($(document.activeElement).attr("class") != "input_textbox"){ ... }
$('*:focus')
(Necro ftw, but still valid and useful)

event.preventDefault() function not working in IE

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

Categories

Resources