Help with keyboard shortcut button toggle

Hi! I’ve been meaning to make a keyboard shortcut for a button on the cards, but the keyboard toggle works on alternate cards (first card it works, second card it doesn’t; third card it works). I’ve modified the code to mirror Anking’s buttons as closely as possible and the card-alternating situation still happens, I’m pretty much at my wits’ end. Would really appreciate some help on this matter, thank you so much!

Relevant code:

<script>
(function() {
    const button = document.getElementById('btn-all');
    const content = document.getElementById('def-all');

    window.toggleBtn = function() {
        if (content.style.display === 'none') {
            button.classList.add('expanded-button');
            content.style.display = 'block';
            content.scrollIntoView({
                behavior: "smooth", //"auto"
                block: "start",
                inline: "nearest"
            });
            button.textContent = 'Hide all (P)';
        } else { //hide content
            button.classList.remove('expanded-button'); 
            content.style.display = 'none';
            button.textContent = 'Show all (P)'; 
        }
    }

    button.addEventListener('click', function() {
        toggleBtn()
    });

    addEventListener("keydown", (event) => {
        if (event.key === "p") { 
            toggleBtn();
        }
    });

})()
</script>

Thanks and cheers.

1 Like

Try checking out the solution to this topic: Issue with shortcut for a button - #11 by jhhr

Here is an excerpt:

3 Likes

You’ll want to unwrap your code from the immediately invoked function expression (meaning, remove the starting (function() { and ending })(); and change const to var), so that you can set the described global variable with var.

I get the use of the IIFE style to avoid global variables but, as you see, it doesn’t protect you if you directly use the document or window object within it. addEventListener is really window.addEventListener and it results in adding a function to the global object.

Also, doing window.toggleBtn = function() { ... is setting a global variable, so you might as well just do function toggleBtn() { ... (this changes nothing functionally, just makes it clearer what is being done IMO)

4 Likes

Thank you so much for both of your replies, they are really helpful.