I have the following code in one page.
Currently works fine on desktop.
Left arrow navigate backwards. Right arrow goes forward. I want to add something on home and end maybe.
The "swipe" part of the code is something I just got after a web search, except a few lines (if ... else ...) after "//DO STUFF HERE".
Testing on mobile (Firefox on Galagy S4): the site works well except this one which is the only to include the code.
Result: swipe not working but also click (not sure if it is called click on mobile) not work, resize not working ... In other word, stuck on the page.
And I don't have much tools to debug on mobile.
function checkKey(event) {
var keyEvent = event || window.event,
keycode = (keyEvent.which) ? keyEvent.which : keyEvent.keyCode;
if(keycode == 37)
NavigateBackward();
else if(keycode == 39)
NavigateForward();
else
{
alert(keycode);
return true
}
return false;
}
document.onkeypress = checkKey;
var swipeFunc = {//Source:https://gist.github.com/localpcguy/1373518
touches : {
"touchstart": {"x":-1, "y":-1},
"touchmove" : {"x":-1, "y":-1},
"touchend" : false,
"direction" : "undetermined"
},
touchHandler: function(event) {
var touch;
if (typeof event !== 'undefined'){
event.preventDefault();
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
case 'touchmove':
swipeFunc.touches[event.type].x = touch.pageX;
swipeFunc.touches[event.type].y = touch.pageY;
break;
case 'touchend':
touches[event.type] = true;
if (swipeFunc.touches.touchstart.x > -1 && swipeFunc.touches.touchmove.x > -1) {
swipeFunc.touches.direction = swipeFunc.touches.touchstart.x < swipeFunc.touches.touchmove.x ? "right" : "left";
// DO STUFF HERE
if(swipeFunc.touches.direction === "left")
alert(swipeFunc.touches.direction);
else if(swipeFunc.touches.direction === "left")
alert(swipeFunc.touches.direction);
else
return true;
return false;
}
default:
break;
}
}
}
},
init: function() {
document.addEventListener('touchstart', swipeFunc.touchHandler, false);
document.addEventListener('touchmove', swipeFunc.touchHandler, false);
document.addEventListener('touchend', swipeFunc.touchHandler, false);
}
};
swipeFunc.init();
Related
I'm developing a web app which listens for combinations of keydown events, e.g. CTRL + B.
My problem is listening for CTRL + ArrowKey on mac. This works fine on PC, but on Mac this is a shortcut to switch between desktops, so the second keydown event (arrow key) does not trigger.
Is there any way to override the mac os CTRL+Arrow shortcut, or listen for this combination in javascript on mac?
document.onkeydown = listenForSecondKey;
function listenForSecondKey(event){
console.log(event.key);
event.preventDefault ? event.preventDefault() : (event.returnValue=false);
if ((holdDown1 == true)&&(holdDown2 == true)){
if (event.which == push){
document.removeEventListener("keydown", keyGoingDown);
if (postcondition){
showPostCondition();
}
else{
killTable();
correctAnswerSubmitted();
}
}
else{
killTable();
incorrectAnswerSubmitted();
}
holdDown1 = false;
holdDown2 = false;
}
}
function keyGoingDown(event){
event.preventDefault ? event.preventDefault() : (event.returnValue=false);
if (event.key == hold1) {
holdDown1 = true;
}
else if (event.key == hold2){
if (holdDown1 == true){
holdDown2 = true;
}
}
else{
//Wrong, but also shouldn't detect push down
}
}
document.addEventListener("keydown", keyGoingDown);
I think this might give an idea.
document.addEventListener('keydown', (e) => {
if ( e.key === 'ArrowLeft' ) {
e.preventDefault() // Stop other operations
}
})
I'm using a open-source game and I'm trying ( for exercise ) to modify it so it can run on Android. The problem is :
In the original game you use space to jump and I need the game to respond to a tactil event so the charachter can actually jump.
The game use this code to keep track of spacebar events :
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for (var code in KEY_CODES) {
if (KEY_CODES.hasOwnProperty(code)) {
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
player.dy = player.jumpDy;
}
So how can I transform the touch event in a spacebar event ?
Thanks in advance for helping, I'm new to coding and I'm trying to learn :)
You could add the following piece of code to your script, to simulate spacebar events from touch events.
document.addEventListener("touchstart", function(e) {
document.onkeydown({ keyCode: 32 });
});
document.addEventListener("touchend", function(e) {
document.onkeyup({ keyCode: 32 });
});
I made a piece of code that moves an element vertically in front of 6 items with arrow up and down. When enter is pressed i will load a set of images with that item. The code works fine but after enter is hit, this piece of code needs to stop, so i can do other things with my arrow keys and enter. Now it just keeps going after enter is hit. I tried it with a var check as you can see but i cant seem to change the variable from within the switch. Someone have an idea how to make this work?
var enterPushed = false;
if(!enterPushed){
document.addEventListener('keydown', function(event){
if(event.keyCode == 38){
console.log("up");
if(margTop > 122){
margTop = margTop - 60;
marginTop();
i = i - 1;
bliep.play();
}
}
if(event.keyCode == 40){
console.log("down");
if(margTop < 422){
margTop = margTop + 60;
marginTop();
i = i + 1;
bliep.play();
}
}
if(event.keyCode == 13){
switch(i){
case 1:
enterPushed = true;
startup(1);
break;
case 2:
enterPushed = true;
startup(2);
break;
case 3:
enterPushed = true;
startup(3);
break;
case 4:
enterPushed = true;
startup(4);
break;
case 5:
enterPushed = true;
startup(5);
break;
case 6:
enterPushed = true;
startup(6);
break;
}
}
});
}
Now you can pass a once boolean in the options object like this: document.body.addEventListener('click', _ => console.log('once'), {once: true});
Source: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Browser compatibility at the moment: Chrome 55, Firefox 50, Safari (WebKit) nightly.
If you want to stop all key events just remove the event listener.
var enterPushed = false;
var handleKeyDown = function(){
if(event.keyCode == 38){
console.log("up");
}
if(event.keyCode == 40){
console.log("down");
}
if(event.keyCode == 13){
console.log('enter');
document.removeEventListener('keydown', handleKeyDown);
}
};
document.addEventListener('keydown', handleKeyDown);
If you want to stop listening for just the enter or a specific key you can add a flag and check against that as well as the keycode. Which looks like what you've almost done here. I finished the logic and reduced the code:
if(event.keyCode == 13 && enterPushed){
enterPushed = true;
startup(i);
}
Funnily enough the method to deattach an event listener is called exactly as one would expect:
removeEventListener(type, listener[, useCapture]):
function listenOnce(node, type, listener, useCapture) {
if (useCapture == null) {
useCapture = false;
}
function wrapper() {
node.removeEventListener(type, wrapper, useCapture);
return listener.apply(this, arguments);
}
node.addEventListener(type, wrapper, useCapture);
}
The web application I work on was designed and developed during the period where there existed only 2-button mice. Now that we have more than 3-button mice available in the market, all those extra buttons are causing havoc while using our application.
My intention is to allow the user to press only the left mouse button and disable all other buttons on his mice. Since, I do not have access to the user's system, I have to achieve this somehow through the browser itself (probably by using JavaScript).
How can I go about solving this problem? Any pointers would be really helpful.
W3C event model is kind enough to pass mouse information through the event object. That means you can actually read which mouse button was clicked. Example
document.body.addEventListener('click', function( event ) {
console.log('mouse button clicked: ', event.which);
}, false);
With that information its fairly trivial to only allow left-clicks, which are represented by the value 1.
document.body.addEventListener('click', function( event ) {
if( event.which === 1 ) {
// do something
} else {
event.stopPropagation();
event.preventDefault();
}
}, false);
It depends on the browser and document mode.
This is how we tweaked prototype.js buttonmaps to work on all browsers. Including IE10 in docmode < 9.
function _isButtonForDOMEvents(event, code) {
return event.which ? (event.which === code + 1) : (event.button === code);
}
//var legacyButtonMap = { 0: 1, 1: 4, 2: 2 };
function _isButtonForLegacyEvents(event, code) {
switch (code) { //Fix where IE10 in DocMode lt9 caused isLeftClick to fail
case 0: return event.button == 0 || event.button == 1;
case 1: return event.button == 4;
case 2: return event.button == 2;
default: return false;
}
}
function _isButtonForWebKit(event, code) {
switch (code) {
case 0: return event.which == 1 && !event.metaKey;
case 1: return event.which == 2 || (event.which == 1 && event.metaKey);
case 2: return event.which == 3;
default: return false;
}
}
I think this is the closest you will get to disabling the buttons
document.addEventListener('click', function( e ){
if(e.which === 2 || e.which === 3) { // 2 = middle scroll button || 3 = right click
e.preventDefault();
e.stopPropagation();
return false;
}
});
Instead of click if it doesn't work you can try 'keydown' or 'keyup'
As a user requirement I have to disable the backspace button from navigating back in the history. I made the following piece of code
//Bind back nutton to prevent escaping the page with backspace
$j(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8)
{
if(event.target == document.body){
if(event.preventDefault()){ event.preventDefault(); }
event.stopEvent();
event.returnValue = false;
}
}
});
This is working perfectly in all the browsers except IE7 and IE8. I cannot bind the input types as exceptions because the content editor in SharePoint allows modification of the text in the elements div, paragraph, etc. The solution is not working in IE8 because the event.target returns the element that is on mouseover when there are no controls that have the focus.
I'd recommend a tweak to Machinegon's fix. The code should also prevent default behavior if the user clicks the backspace key in a readonly input control of type text.
if ((nodeName === "input" && event.target.type === "text") ||
nodeName === "textarea") {
doPrevent = event.target.readOnly;
}
Solved by myself, case closed.
EDIT: Working in 2012 with SharePoint 2010 and jquery 1.x, not sure about today.
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function (event) {
if (event.keyCode === 8)
{
var doPrevent = true;
//Chrome, FF, Safari
if(event.target == document.body){
doPrevent = true;
}
//IE
else
{
var nodeName = event.target.nodeName.toLowerCase();
if((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
{
doPrevent = false;
}
var SPEditTabInstance = $(document).find("li[id='Ribbon.EditingTools']");
if(SPEditTabInstance != "undefined" && SPEditTabInstance != null && $(SPEditTabInstance).children().length > 0){
doPrevent = false;
}
}
if(doPrevent)
{
//Chrome, FF, Safari
if(event.preventDefault()){ event.preventDefault(); }
//IE
else
{
event.returnValue = false;
}
}
}
});
Try pushing back to the person(s) creating the requirements that breaking a ubiquitous and important function of all browsers is not a particularly great idea from a usability perspective. The costs of doing so (including time spent explaining to users why thier browser "don't work no more") will greatly outweight the costs of having the back button be a bit annoying occaisionally.
Machinegon's answer works well, I'm just adding to it to handle one more case.
If the input boxes are readonly or disabled, and if you hit backspace on them, then it goes to previous page. So the following code will work to handle that scenario:
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function(event) {
if (event.keyCode === 8) {
var doPrevent = true;
//Chrome, FF, Safari
if (event.target == document.body) {
doPrevent = true;
}
//IE
else {
var nodeName = event.target.nodeName.toLowerCase();
if (((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
&& !event.target.disabled && !event.target.readOnly) {
doPrevent = false;
}
}
if (doPrevent) {
//Chrome, FF, Safari
if (event.preventDefault()) {
event.preventDefault();
}
//IE
else {
event.returnValue = false;
}
}
}
});