Home > database >  How can I access the result of this function on this other function?
How can I access the result of this function on this other function?

Time:02-02

So i have this text input field and I have the showKeyCode() function which gets the value from the text input and prints the keycode representation of the pressed key into the console.

function showKeyCode() {
$('#inputfield').keyup(function(e){
   $(this).val(String.fromCharCode(e.keyCode)); 
   console.log(e.keyCode);
});
}
const r4 = document.querySelector("#inputfield");
r4.addEventListener('input', showKeyCode2);

Now i want to get this value and use it at the function below.


 $(document).keydown(function(e) {
    if (e.which ==  [I WANT TO PUT THE RESULT FROM showKeyCode() HERE] ){
      document.querySelector('#test').click()
      console.log("Clicked");
    }
});

Lets summarize what I'm trying to do here. If you are a gamer you must have used the keybinds for example : Press [M] to show minimap. Press [H] to show hud.

Here im trying to make the user customize the keybind by typing it into the text field. The showKeyCode() function gets the Character and converts it into a keycode which ill use in the second function.

I couldve typed the keycode directly into the script like this

if (e.which ==  84 ){}

but i wanted the user to change it inside the game.

CodePudding user response:

Technically "You can't" But there's a hacky and dirty workaround. Global variables.

//outside
let value = '';

function showKeyCode() {
  $('#inputfield').keyup(function(e){
     $(this).val(String.fromCharCode(e.keyCode)); 
     value = e.keyCode;
  });
}


$(document).keydown(function(e) {
    if (e.which ==  [value] ){
      document.querySelector('#test').click()
      console.log("Clicked");
    }
});

This should work if sowKeyCode was called before a keydown was made

Now, I DO NOT RECCOMMEND using global variables but sometimes its the only way on the approach, perhaps you can use a different method like putting this inside a class or using other libraries that are great with state tracking.

  •  Tags:  
  • Related