I am trying to embed my JavaScript code in to a StoryLine Scorm course.
I need to change the variable KeyPressed_WrongKey
if user click any key except "Alt" or "=".
My JavaScript code looks like this.
var player = GetPlayer();
var isPressedCtrl = 0;
$(document).keyup(function (e) {
if (e.which == 18) isPressedCtrl=0;
}).keydown(function (e) {
if (e.which == 18) isPressedCtrl=1;
if (e.which == 187 && isPressedCtrl == 1) {
player.SetVar("KeyPressed", 1); //run if Alt+= pressed
}
if (e.which != 187 || e.which != 18) {
player.SetVar("KeyPressed_WrongKey", 1); //run if pressed anything else
}
});
When I press Alt or =, the second IF is true too...
Can anybody help with this?
How can I correct the script for pressing any key except what is needed?
More of a suggestions than a solution. That is, to drop e.which
and use e.code
instead.
Why? Because which
is deprecated and code
is easy to read without the need for looking up what the number means.
Also, your question does not seem to match your code. The logic seems to be all over the place compared to the question.
If my understanding is correct, you can replace most of your code with one line.
function testKey(e) {
var isPressedCtrl = ((e.code == "Equal") || (e.code == "AltLeft") || (e.code == "AltRight"));
console.log("isPressedCtrl:["+ isPressedCtrl +"] e.code:["+ e.code +"]");
// if (isPressedCtrl) { player.SetVar("KeyPressed_WrongKey", 1) }
// but, you could also do:
// player.SetVar("KeyPressed_WrongKey", isPressedCtrl);
}
// so the code works in the sample window
window.onload = function() {
var d = document.getElementById("testBox");
d.addEventListener("keyup",testKey,false);
}
<input type="text" id="testBox" placeholder="text box" />