Press any key except needed by script

Jun 17, 2020

Hello.

I try to embed my JavaScript code to StoryLine Scorm course.

I need to change variable KeyPressed_WrongKey if user click any key accept "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...

Anybody could to help with it?

How to write correct script for pressing anykey except needed?

3 Replies
Walt Hamilton


if (e.which != 187 || e.which != 18)

This line will always be true:

The OR operator (||) means that it is true if even one of the two conditions is True.

1. If the keypress was not 187 or 18, obviously the first half is NOT 187, and the statement is True.

2. If the keypress was 18, then the first half is NOT 187, and the statement is True.

3. If the keypress was 187, then the first half IS 187, and is false, but the second half is NOT 18, and is True, so the statement is True.

 

What may work for you is something like  if( isPressedCtrl != 1 || e.which != 187)  EDIT: Now that I think about it, this may not work, because keyup always happens after keydown, no matter which order they are in the script. So if keydown is 18, then the keyup function will set IsPressedCtrl to 0, so this suggestion is unreliable.

But really, it seems like a lot of extra work.  If a key is pressed, it is either the right key, or it is the wrong key. There is no third option. So the easy method is if the right conditions are met, set KeyPressed = 1, then use an ELSE to set KeyPressed_WrongKey =1.

Still easier is to Set KeyPressed to False in SL, and call the script. If the right key is pressed, change it to True, if not, forget changing it, and leave it False.

This discussion is closed. You can start a new discussion or contact Articulate Support.