Help detecting Keyboard or Gamepad Input to change Menu Buttons

Hey all,

I'm still new to RMMZ and Javascript in general. I've had some experience in the past during early college with C++ and Java but some time has passed since then. Currently in my project I'm using VisuStella plugins, specifically in this example would be the VisuStella Core Engine. There is an option in this plugin to change the Menu Button Assist icons (so listing Z as Confirm/Accept and X as Cancel/Back) and showing icons for both Z and X. What I'm looking to do is to change these icons depending upon whether the player is using a gamepad or keyboard. I've taken a look at the GamePad API but I'm still struggling to understand how to accomplish this efficiently.

Here's what I'm doing at the moment. I have a common event set up to run as a parallel process on every map with this script:

var swId = 200; // ID of game switch to toggle if a gamepad is recognized
var o = navigator.getGamepads();

window.addEventListener('gamepadconnected', event => {
$gameSwitches.setValue(swId, true);
event.gamepad;
});
window.addEventListener('gamepaddisconnected', event => {
$gameSwitches.setValue(swId, false);
});

(the line var o = navigator.getGamepads(); isn't really necessary but is left over from code I found on these forums)

following this is a conditional statement with the switch 200 which will change a variable containing the icon information with a string pointing to the correct icon.
example.PNG


This works, but not how I want it to. When I test this, the menu icons will change as soon as I start pressing buttons on the controller and will change back to keyboard when it is disconnected. But if I were to save the game while the controller is connected, the switch to determine if the controller is connected stays on and persists when the game is loaded back in. So at that point I'm stuck with gamepad icons until I plug the gamepad back in and disconnect it.

Is there a better way to accomplish this? This is my first time posting here so sorry if I sound a little confusing! I'd greatly appreciate any help or advice. I'm currently looking into learning Javascript a little more as I'm still a newbie.

Thank you.

Original thread: https://forums.rpgmakerweb.com/threads/help-detecting-keyboard-or-gamepad-input-to-change-menu-buttons.129753/