I am using impress.js as a plugin and I am trying to overwrite the keycode definitions without altering impress.js itself (otherwise during the next update the changes will be overwritten.)
This is how the keycode definitions are implemented in impress.js:
// KEYBOARD NAVIGATION HANDLERS
// Prevent default keydown action when one of supported key is pressed.
document.addEventListener( "keydown", function( event ) {
if ( event.keyCode === 9 ||
( event.keyCode >= 32 && event.keyCode <= 34 ) ||
( event.keyCode >= 37 && event.keyCode <= 40 ) ) {
event.preventDefault();
}
}, false );
if ( event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) {
return;
}
if ( event.keyCode === 9 ||
( event.keyCode >= 32 && event.keyCode <= 34 ) ||
( event.keyCode >= 37 && event.keyCode <= 40 ) ) {
switch ( event.keyCode ) {
case 33: // Page up
case 37: // Left
case 38: // Up
api.prev();
break;
case 9: // Tab
case 32: // Space
case 34: // Page down
case 39: // Right
case 40: // Down
api.next();
break;
}
event.preventDefault();
}
}, false );
This is how I am trying to overwrite their definition (in a separate js file, but code is executed after impress.js is initiated):
- space key should call pause
the other keys should have no effect.
// Bind keyboard events.. document.addEventListener('keyup', function (event) {
if (event.keyCode === 9 || (event.keyCode >= 32 && event.keyCode <= 34) || (event.keyCode >= 37 && event.keyCode <= 40)) { switch (event.keyCode) { // ..left key arrow, go to previous slide case 37: return deck.prev(); break; // ..right key arrow, go to previous slide case 39: return deck.next(); break; case 32: // Space return deck.pause(); break; case 9: // Tab case 33: // Page up case 38: // Up case 34: // Page down case 40: // Down return; } event.preventDefault(); }
}, false);
However, the function of the keys is not altered.
Can keycodes be overwritten and how can I achieve this?
addEventListener
does not overwrite previously added event listeners, this is one of its advantages over using the on* event properties / attributes.In order to do what you want you are going to need to add your own
impress:init
event listener, before the one added by impress, do the same setup as the library does, changing what needs changed, and then calling stopImmediatePropagation().stopImmediatePropagation
will prevent any other listeners of the same type from being executed, meaning impress'simpress:init
event listener will not be triggered.Demo