key down listner event not working in firefox - javascript

I have a 'keydown' event on javascript for navigating table using arrow keys:
my code as follows:
document.onkeydown= function() { keyDown();};
The implementation code as follows:
function keyDown(e){
var evt=(e)?e:(window.event)?window.event:null;
var key = evt.keyCode || evt.which;
if(key==38 || key==40){
alert("working");
}
}
How can I make it works on all browsers? What I am doing wrong here?

You need to pass the event variable that the system passes in to your function or use the standardised addEventListener method:
// Passing the event
document.onkeydown = function(e) { keyDown(e); };
// Using event listeners
document.addEventListener('keydown', keyDown, false);
Then you should rely on the event passed - do not use window.event - if the event is not passed to your function you have bigger issues to worry about than finding the event.
function keyDown(e){
if(e.which == 38 || e.which == 40){
alert("working");
}
}
I would learn more about the addEventListener method as assigning functions to the documents own onEvent attributes is not advised. What if you want to change this later? What if you want to add some code some of the time? Event Listeners are great for that and they don't modify the default behaviour here. You can add and remove these on the fly, making it much more versatile. Have a read here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Related

how to write a jasmine spec for triggering a on event in jquery

how to write a jasmine spec for triggering a on event in jquery ?
$('#myid').on('keyup', function (event)
{
if(event.which === 13)
{
event.preventDefault();
myfunc(id);
}
});
those lines are not covered by jasmine spec how to write jasmine specs for those lines.
only triggering event didnt cover those lines so help me here
I don't know how you wrote your spec but try the below code
var event = $.Event("keyup");
event.which = 13;
$("#myid").trigger("keyup");
// expectations follow
If it still doesn't work, try using a separate named function instead of anonymous function as follows:
$('#myid').on('keyup', keyupHandler.bind(this));
function keyupHandler() {
if(event.which === 13){
event.preventDefault();
myfunc(id);
}
}

Javascript can't access keyboard event in an onblur function in IE 11 but not IE 9

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.

How do i get multiple independant document.onkeydown events to work?

I'm working on my personal website and I've build in some easter egg hotkeys. On every page pressing the 'm' key should hide the menu and pressing the 'g' key should launch a game ontop of the current page. On another page I have the 't' and 'l' keys perform other CSS changes. On every page the game and menu keys operate as expected except for the page with the listener for 't' and 'l'. There is clearly some kind of conflict preventing them all from working on each page. I believe it is because I have the listeners declared across three different files. I would like to keep it that way so that my site is more modular (i.e. I can easily transfer the js file for the game to any other website). Any ideas?
First listener, 'm' key: (nav-script.js)
document.addEventListener('keydown', function(evt){
var evt = evt || window.event;
if(evt.keyCode == 77){
showNav();
}
},false);
Second listener, 'g' key: (clickgame.js)
document.onkeydown = enable;
function enable(event){
// Enables/disables the game
var event = event || window.event;
if(event.keyCode == 71 && !enabled){ // 71 is the code for the 'G' key
game = true;
enabled = true;
setup();
}else if(event.keyCode == 71){
game = false;
enabled = false;
quitgame();
}
}
Third listener, 'l' and 't' keys: (project-focus.js)
document.onkeydown = focusFeatures;
function focusFeatures(event){
var event = event || window.event;
if(event.keyCode == 76){
lightswitch();
}else if(event.keyCode == 84){
textswitch();
}
}
The document.onkeydown = assignment overwrites all previously assigned handlers. You need to use addListener to effectively attach multiple handlers for the same event.
Or, you could just use jQuery as that will make things a whole lot easier.
When you do this:
document.onkeydown = focusFeatures;
You are replacing every other onkeydown listener with focusFeatures.
This is the same for document.onkeydown = enable.
You should do this instead:
document.addEventListener('keydown', enable, false); // for the games
document.addEventListener('keydown', focusFeatures, false); // for the focus features
Plus you should first declare the function, and then assign it to the listener.
Am I correct in understanding that each JS file is loaded on the page? If so then the last file to be loaded is clobbering the previous document.onkeydown handler.
Each document can have only one document.onkeydown handler so you will have to do some clever event dispatching to be sure they are propagated to every piece of code that needs it. Common libraries such as jQuery and Google Closure will handle this for you. Here is an example in jQuery:
$(document).keydown(function(e) {
if (e.keyCode == 76) {
window.console.log("pressed l!");
}
});
$(document).keydown(function(e) {
if (e.keyCode == 71) {
window.console.log("pressed g!");
}
});
And a link to it working in action: http://jsfiddle.net/v7v4L/

Am I guaranteed to get an event object with a target property in a JavaScript event handler?

Just as the title says I'm curious if I'm guaranteed to get an event object inside of a Javscript event handler. The main reason I'm asking is that I've seen onClick event handlers that look like this.
function(e) {
if(e && e.target) {
//Code in here
}
}
Which seems wrong to me, but I know Javascript can have minor variances across browsers. Is there some time at which it's appropriate to check for the event object? Or the event target? It seems like you'd have to have a target to fire off an event.
No. Older versions of windows don't pass the event argument to the event handler. They have it in a global variable window.eventand the target is in .srcElement. Other than that exception, you should always get an event structure.
A work-around for the older versions of IE is this:
function(e) {
if (!e) {
e = window.event;
e.target = e.srcElement;
}
// code that uses e here
}
But, usually, this is addressed at a higher level by the function that you use to install event handlers. For example:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
window.event.target = window.event.srcElement;
return(fn.call(elem, window.event));
});
}
}
Depending on the browser compatibility they are looking to achieve, this may be an acceptable solution. However, for older version of IE, the event object is a part of the global window object. In order to get the target in that case you would want window.event.srcElement, as there is no target.
More info here on the event object for IE.

How do I consume a key event in javascript, so that it doesn't propagate?

How do I consume a key event in javascript, so that it doesn't propagate?
If you don't want the event to propagate and you're not using jQuery (or another library that wraps native browser events), you need to use the event's stopPropagation() method in most browsers and its cancelBubble property in IE. Don't bother with return false or preventDefault(): those only affect whether the native browser action happens for the event and have nothing to do with propagation.
For example:
document.onkeypress = function(evt) {
evt = evt || window.event;
if (typeof evt.stopPropagation != "undefined") {
evt.stopPropagation();
} else {
evt.cancelBubble = true;
}
};
Try preventDefault and/or stopPropagation.

Categories

Resources