javascript stop all functions when game is over - javascript

I need to stop this function from executing:
document.addEventListener("keypress", function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
checkKey(charStr);
//check loss
if (attempt == 0) {
gameLost();
}
//check win
underscoreRemain = nameReform.includes("_");
if (!underscoreRemain) {
gameWon();
}
document.getElementById("attempt").innerHTML = attempt;
});
Basically, when the game is either won or lost, it won't take any more key pressed, hence no execution of the rest of my functions. I've looked on w3school and stackoverflow, but the removeEnventListener and other suggested methods don't work.

Remove the event listener by passing the original function object to removeEventListener at the appropriate time.
Notice that I gave the function a name.
document.addEventListener("keypress", function handler(evt) {
// evt = evt || window.event; // This line is unnecessary
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
checkKey(charStr);
//check loss
if (attempt == 0) {
gameLost();
// Remove the listener
this.removeEventListener(event.type, handler);
}
//check win
underscoreRemain = nameReform.includes("_");
if (!underscoreRemain) {
gameWon();
// Remove the listener
this.removeEventListener(event.type, handler);
}
document.getElementById("attempt").innerHTML = attempt;
});

Related

How to access function from event listener. JavaScript

I have an event listener in header:
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if(key == 27) {
var panel = document.getElementById('largeImgPanel');
hideMe(panel);
}
if(key == 39) {
arrow_right.onclick = onRight; //Wrong
}
};
Lower i have a function:
window.onload = function() {
...
var onRight = function showNext(img_thumb) {
index = index + 1;
document.getElementById('largeImg').src = arr_big[index].src;
showLargeImagePanel();
unselectAll();
};
arrow_right.onclick = onRight;
My question is:
How i can "execute" onRight variable from event listener?
Allow onRight to be a global variable. Although this is not always desirable, in this instance it will work. Keep in mind, it is best not to pollute the global namespace.
window.onRight = function showNext(img_thumb) {...
and then later you may access it the same way
arrow_right.onclick = window.onRight;

Not all code paths return a value (JavaScript)

document.getElementById('search_field').onkeypress = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
window.location.href = '/search/?s=' + $('#search_field').val();
return false;
}
};
The last bracket show me an error, not all code paths return a value, what seems to be problem here ?
Thanks
Try this :
document.getElementById('search_field').onkeypress = function(e) {
if (!e) {
e = window.event;
}
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
window.location.href = '/search/?s=' + $('#search_field').val();
return false;
}
return true;
};
More... I think that you may not use both pure javascript and jquery
So you'd rather choose between
JAVASCRIPT :
document.getElementById('search_field').onkeypress = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
window.location.href = '/search/?s=' + document.getElementById('search_field').value;
return false;
}
return true;
};
JQUERY
$( "#search_field" ).keypress(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
window.location.href = '/search/?s=' + $(this).val();
return false;
}
return true;
});
End your function with return true.
If any other key then 13 is pressed the flow should just continue normally.
Ignore your tool. Event handlers do not have to return a value in every occasion, it is fine if only a particular path does return false.

Block F5 key using JavaScript

I have written some code to block the F5 key on web page. It's working fine except when I have to display a large amount of data. If you press the F5 key during the loading duration in which the HTML and JavaScript code is generated, my page gets refreshed.
Here is the code that I am using to block the F5 key:
document.onkeydown = fn;
var fn = function (e){
if (!e)
var e = window.event;
var keycode = e.keyCode;
if (e.which)
keycode = e.which;
var src = e.srcElement;
if (e.target)
src = e.target;
// 116 = F5
if (116 == keycode) {
// Firefox and other non IE browsers
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation();
// Internet Explorer
}else if (e.keyCode){
e.keyCode = 0;
e.returnValue = false;
e.cancelBubble = true;
}
return false;
}
});
I think this code is not working when the HTML and JavaScript code is generating.
I have some very simple code for preventing F5 that I use myself. Works in IE, Chrome and Firefox:
function disableButtonsDown(e) {
if ((e.which || e.keyCode) == 116) e.preventDefault();
};
$(document).on("keydown", disableButtonsDown);
document.onkeydown=disableF5;
var version = navigator.appVersion;
function disableF5(e)
{ var keycode = (window.event) ? event.keyCode : e.keyCode;
if ((version.indexOf('MSIE') != -1))
{ if (keycode == 116)
{ event.keyCode = 0;
event.returnValue = false;
return false;
}
}
else
{ if (keycode == 116)
return false;
}
}

onkeydown and onkeyup events don't work on Internet Explorer 8

My code works without problems on IE9/IE10, FF, Chrome and opera but on older Internet Explorer no Keyboard input is handled.
I have the following code for handling events. It should only fire when a new button is pressed.
lastEvent = void 0;
heldKeys = {};
window.onkeydown = function(event) {
if (lastEvent && lastEvent.keyCode === event.keyCode) {
return;
}
lastEvent = event;
heldKeys[event.keyCode] = true;
switch (event.which) {
case 80:
return myamp.userInput("positiv");
case 81:
return myamp.userInput("negativ");
}
};
window.onkeyup = function(event) {
lastEvent = null;
return delete heldKeys[event.keyCode];
};
You need to bind to the document, not window.
window.onkeyup = function(event) {
window.onkeydown = function(event) {
needs to be
document.onkeyup = function(event) {
document.onkeydown = function(event) {
Try
lastEvent = void 0;
heldKeys = {};
window.onkeydown = function(event) {
event = event || window.event; //IE does not pass the event object
if (lastEvent && lastEvent.keyCode === event.keyCode) {
return;
}
lastEvent = event;
heldKeys[event.keyCode] = true;
var keyCode = event.which || event.keyCode; //key property also different
switch (keyCode) {
case 80:
return myamp.userInput("positiv");
case 81:
return myamp.userInput("negativ");
}
};
window.onkeyup = function(event) {
event = event || window.event;
lastEvent = null;
return delete heldKeys[event.keyCode];
};
You have to use normalized key code. Like this:
var keyCode = event.which || event.keyCode;
I tried different solutions but these still did not work correctly in IE8. What I came up with that worked is this:
window.onkeyup = function(e) {
e = (e) ? e : window.event; // check if e is defined
var kc = (e) ? e.which : e.keyCode; // assign keyCode
key = (key === undefined) ? e.keyCode : kc; // if keyCode still undefined, reassign it
if (kc == 13) {
//enter was pressed
}
// other code
}

Javascript on second keypress

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.
var escapeCount = 0;
function reset() {
escapeCount = 0;
setTimeout('reset();', 1000);
}
window.onload = function() {
reset();
};
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (code == 27) escapeCount +=1;
if (escapeCount == 2) {
// stuff on second escape
}
};
Is there a better way to do this? Thanks
It would make sense to reset after 1 second has passed since the last character was pressed. Example:
var lastChar = -1;
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (lastChar == code) {
// Same key was pressed twice in a row within 1 second.
} else {
lastChar = code;
setTimeout(function() {lastChar = -1;}, 1000);
}
};
Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.
It's probably easier to forget the timeout and just remember the time of the last keypress instead:
var lastescapetime= null;
document.onkeyup= function(event) {
if (event===undefined) event= window.event;
if (event.keyCode===27) {
var now= new Date().getTime();
if (lastescapetime!==null && now<lastescapetime+1000) {
alert('You double-escaped!');
lastescapetime= null;
} else {
lastescapetime= now;
}
} else {
lastescapetime= null;
}
};

Categories

Resources