Search code examples
javascripthtmltoggleswap

Javascript - Swap Divs on KeyDown


I can swap two divs by clicking on a link, as shown in the following code, but how do I swap them by pressing a key?

This is what I have:

function SwapDivs(div1, div2) {
        d1 = document.getElementById(div1);
        d2 = document.getElementById(div2);
        if (d2.style.display == "none") {
            d1.style.display = "none";
            d2.style.display = "block";
        } else {
            d1.style.display = "block";
            d2.style.display = "none";
        }
    }
<p>
    <a href="javascript:SwapDivs('FirstDiv','SecondDiv')">Swap Divs</a>
</p>


<div id="FirstDiv" style="display:block">
    <p>
        This div is displayed when the page opens.
    </p>
</div>

<div id="SecondDiv" style="display:none">
    <p>
        This div is displayed when the link is clicked.
    </p>
</div>

I have used OnKeyDown before, but I can't figure out how to apply it here...

This just doesn't work:

    document.body.addEventListener("keydown", function(event) {
        if (event.keyCode === 32) {
            function SwapDivs(div1, div2);
        }
    });


Solution

    1. If you call a Function you don't write the "function" keyword before it.

    2. You passed two non-existent Variables called div1 and div2 in the function SwapDivs which was called inside the event listener.

    3. If you are adding an Event Listener to the body, you have to add the <body> tag.

    As an example I used "Arrow Down Key" which has the keycode 40.

        document.body.addEventListener("keydown", function(event) {
            if (event.keyCode === 40) {
               SwapDivs('FirstDiv','SecondDiv');
            }
        });

    Here's a codepen: https://codepen.io/anon/pen/MqZomW