Reputation: 5294
I have an issue concerning the keyboards events in JS.
First of all, please do not answer me to use jQuery methods, I know most of it (bind/unbind, on/off, one...) but I work with an internal framework that have to work without jQuery, even if jQuery is used on most of our projects.
So, I have a module, in fact a swipe tool based on Swipe.js and extended to work on web and mobile environments (compatibility needed for IE 7+, WebKit (Chrome & Safari), Moz, Opera and IE10 / Windows Phone)
In do not have any problem with mouse/touch events, the binding and unbinding methods inspired from the mobile HTML5 BP seems to work very well with a small correction for the detachEvents method.
And then I would to implement a keyboard control feature based on 'keydown' events. (BTW, I am not sure to make a good difference between keydon and keypress events, except the keypressEvent.preventDefault() do not prevent the small scroll effect, so I use keydown.)
As it is possible to add many Swipes on the same page, I start to listen the keydown events only when any Swipe is focused (Note that I add a "tabindex" attribute to allow the element to get focused).
<div id="swipe1" class="swipe" tabindex='0'>
<ul>
[...]
</ul>
</div>
Then when the Swipe handle a 'touchstart' / 'click' / ' MSPointerDown' event, I focus it :
onTouchStart: function(e) {
this.container.focus(); // Refers to the div#swipe1.swipe element
[...]
return false;
}
onFocus: function (e) {
if (this.activateKeyboardControls) { // Keyboard control is optional
this.addListener(document, 'keydown', this, true);
}
}
onBlur: function (e) {
if (this.activateKeyboardControls) { // Keyboard control is optional
this.removeListener(document, 'keydown', this, true);
}
}
But unfortunately, the removeListener does not work.
I mean, when the element loses the focus (blur event fired), it still handle the keydown events...
Is it because it is binded on the document object ? I have read some solutions working with some booleans but I am looking for a cleaner way the manage it.
This is annoying, because when I give the focus to many Swipes, each of them is swiping when I press the keyboard.
Upvotes: 3
Views: 1888
Reputation: 5294
I'm not sure of the reason why my answer has been deleted - more than 2 weeks after posting - but anyway, this is how I solved it :
It comes from the 'type' parameter of the addEventListener / attachEvent method, the first of one so...
I bind it on the object instead of on the window, and without bubbling.
var target = e.target || e.srcElement;
if (this.activateKeyboardControls) {
this.addListener(target, 'keydown', this, false);
}
Upvotes: 1