Managing JavaScript hotkeys in Chrome Browser - javascript

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.

Related

In IE8: Create a custom event in vanilla JS and pick it up in Jquery

All of this is happening for IE8.
Due to script import orders, I'm having a bit of code being executed before JQuery is loaded where I need to fire a custom event.
This event will be picked up later in another bit of code when I'm sure JQuery will have been loaded. So I'd like to use JQuery to pick up this event.
I saw this previously asked question: How to trigger a custom javascript event in IE8? and applied the answer, which worked, but when I'm trying to pick up the Event via JQuery, then nothing happens.
Here's what I've tried:
function Event() {}
Event.listen = function(eventName, callback) {
if (document.addEventListener) {
document.addEventListener(eventName, callback, false);
} else {
document.documentElement.attachEvent('onpropertychange', function(e) {
if (e.propertyName == eventName) {
callback();
}
});
}
};
Event.trigger = function(eventName) {
if (document.createEvent) {
var event = document.createEvent('Event');
event.initEvent(eventName, true, true);
document.dispatchEvent(event);
} else {
document.documentElement[eventName] ++;
}
};
Event.listen('myevent', function() {
document.getElementById('mydiv-jquery').innerText = "myevent jquery";
});
$(document).on('myevent', function() {
document.getElementById('mydiv-vanilla').innerText = "myevent vanilla";
});
Event.trigger('myevent');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv-jquery">Nothing</div>
<div id="mydiv-vanilla">Nothing</div>
PS: The snippet doesn't seem to work properly in IE. Here's a jsfiddle that should be working.
There are a few problems with this code.
You shadow the built-in window.Event without checking if it exists; this could cause problems for other scripts.
You don't preserve the this binding when calling the callback from your onpropertychange listener. You should apply the callback to the document rather than calling it directly so the behavior will be as close as possible to addEventListener.
You attempt to increment document.documentElement[eventName] while it is undefined. The first call will change the value to NaN, so onpropertychange should pick it up, but on subsequent calls it will remain NaN.
You make no attempt to have .on() recognize your Event.listen function, so naturally the code in Event.listen will never be executed from a listener attached with .on().
Have you tried using Andrea Giammarchi's CustomEvent shim?

Prototype js - keyup event not working

I am trying to use keyup event on some text inputs using prototype js. But the event is never fired. here is my code:
document.observe("dom:loaded", function() {
$$('.inputclass').each(function(element) {
console.log(element);
element.observe('keyup', alert("here"));
});
});
The console.log works fine and I can see the elements logged in chrome dev tools but the alert never happens.
I have a simple textarea on the page like so:
<textarea class="inputclass"></textarea>
Firstly you need to wrap the alert('here') in a anonymous function as the observe() method is expecting a function passed to it not the return of alert() (which is undefined) like this.
function(){
alert('here');
}
Secondly you can use some of the array iterators to do the same thing over all the array objects like this
$$('.inputclass').invoke('observe','keyup',function(){
alert('here');
});

How to register document.onkeypress event

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

JavaScript error "Function is expected"

I have several listeners like this, which listen to click and then displays content within <div id="c50"><a hre...>CONTENT</a></div> (in this case). Everything works in Opera, Chrome and FF, but not in IE.
google.maps.event.addListener(pano50, 'click', function() {
fireEvent(document.getElementById("c50").getElementsByTagName("a")[0], 'click');
})
Chrome javascript console tool displays this error after click (but works fine):
Uncaught TypeError: object is not a function
but traditionally, IE8 displays:
Function expected on line 817
which is the first line of code above and do nothing after click. Thank you for any advice!
EDIT: here is the fireEvent function:
function fireEvent(element, event) {
if (document.createEventObject){
/* for IE */
return element.fireEvent('on' + event, document.createEventObject());
}else{
/* for other browsers */
var evt = document.createEvent('HTMLEvents');
evt.initEvent(event, true, true);
}
return !element.dispatchEvent(evt);
}
You've got MooTools running on your page. MooTools overrides IE's built-in element.fireEvent() method with its own normalized method that works for all browsers. MooTools' version of fireEvent() expects "click" instead of "onclick".
You can fix this one issue by simply changing your fireEvent function to use "click" instead of "onclick":
/* for IE */
return element.fireEvent(event, document.createEventObject());
But, since MooTools normalizes element.fireEvent to work with all browsers, you may be able to ditch your fireEvent function, and instead just call element.fireEvent() directly.
You may have bigger problems. You are using MooTools and jQuery side by side which is ok, but if you don't know what you are doing, you can get into trouble quickly.
It's possible it's complaining because
document.getElementById("c50").getElementsByTagName("a")[0]
is not a function. Where is the fireEvent function coming from?

JavaScript event handlers -why no alert?

I'm a newbie at JavaScript trying to learn event handlers. Looking at this fiddle http://jsfiddle.net/mjmitche/uV4kv/ can anyone tell me why the pop up is not appearing when the link is clicked?
I've also copied the code below
click me
function addEventHandler(oNode, sEvt, fFunc, bCaptures){
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+sEvt, fFunc);
else
oNode.addEventListener(sEvt,fFunc,bCaptures);
}
function onLinkClicked(e) {
alert("you clicked the link");
}
function setUpClickHandler(){
addEventHanlder(document.getElementById('clickLink'), "click", onLinkClicked, false);
}
addEventHandler(window,"load",setUpClickHandler,false);
There are basically three problems:
You have some typos, e.g. "Hanlder" instead of "Handler" and "Sevt" instead of "sEvt".
The code is already run after page load, so the event handler you add to window will never be called. Change in jsFiddle from onLoad to no wrap (head).
You "IE detection" does not work. I get this error in Chrome:
Uncaught TypeError: Object http://fiddle.jshell.net/_display/# has no method 'attachEvent'.
Better would be to test whether the function window.attachEvent exists. I also think that window.event is only available when an event is raised.
If this is corrected, your code will run (DEMO).
Further notes:
Testing which method is supported (i.e. attachEvent or addEventListener) on every call of your function is unnecessary. It won't change during the life of the page. Better is to test only once at the beginning. Example:
var addEventHandler = (function() {
if(window.attachEvent) {
return function(oNode, sEvt, fFunc) {
oNode.attachEvent("on"+sEvt, fFunc);
};
}
else {
return function(oNode, sEvt, fFunc, bCaptures) {
oNode.addEventListener(sEvt,fFunc,bCaptures);
};
}
}());
This assigns a function the supported function to addEventHandler.
A couple of problems:
You have a recurring typo, "Hanlder" instead of "Handler". There are at least two, one where you do your setUpClickHanlder (sic) function, and one within it (addEventHanlder).
Also, you have "Sevt" where you mean "sEvt". (JavaScript is case sensitive.)
Let tools help you. Use a browser that gives you a console showing errors. Use a debugger for single-stepping through code, looking at variable values at runtime with inspectors, etc.
Your addEventHandler needs adustment:
function addEventHandler(oNode, sEvt, fFunc, bCaptures) {
oNode.attachEvent ? oNode.attachEvent ("on" + sEvt, fFunc) :
oNode.addEventListener (sEvt, fFunc, bCaptures);
}
It is in event handlers themselves that you need to check for window.event

Categories

Resources