How to toggle the movement between two divs?

I have made two boxes with div to move them with arrow keys and it works just fine with a single box. But when I added the second box, they both started to move at the same time even though I’ve given them different IDs. What I want to achieve is that when the user hits Spacebar, the first box to be disabled and the second box activated. I’ve also searched up for something similiar but I could not find anything. So I have made a JSFiddle here so you can take a closer look.

And this is my JQuery code:

<script>
        jQuery(document).keydown(function (e) {
            switch (e.which) {
                case 37:
                    jQuery("#cube").stop().animate({ left: '-=10' });
                    break;
                case 38:
                    jQuery("#cube").stop().animate({ top: '-=10' });
                    break;
                case 39:
                    jQuery("#cube").stop().animate({ left: '+=10' });
                    break;
                case 40:
                    jQuery("#cube").stop().animate({ top: '+=10' });
                    break;
            }
        });

        var space = false;
        jQuery(function () {
            jQuery(document).keydown(function (evt) {
                if (evt.keyCode == 32) {
                    space = true;
                }
            });
        });
        if (space = true) {
            jQuery(document).keydown(function (e) {
                switch (e.which) {
                    case 37:
                        jQuery("#cubetwo").stop().animate({ left: '-=10' });
                        break;
                    case 38:
                        jQuery("#cubetwo").stop().animate({ top: '-=10' });
                        break;
                    case 39:
                        jQuery("#cubetwo").stop().animate({ left: '+=10' });
                        break;
                    case 40:
                        jQuery("#cubetwo").stop().animate({ top: '+=10' });
                        break;
                }
            });
        }
</script>

Any help is much appreciated, thanks in advance.


Source: html

Leave a Reply