I am trying to add multiple event listeners to elements that are being dynamically added to a page. I have attempted to use the on() function, as instructed in many posts but none of them seem to work for. When the page is clicked, a new should be added, with formatting determined by the correct CSS class. When a particular is focused, it should be movable using WASD and the jquery animate(). Here is what I have right now:
$(document).ready( function() {
var $index = 0;
$('div').on('keydown', 'div' , function(key) {
    switch(parseInt(key.which,10)) {
        case 87: //W
            $(this).animate({top: '-=10px'}, 'fast');
            break;
        case 65: //A
            $(this).animate({left: '-=10px'}, 'fast');
            break;
        case 83: //S
            $(this).animate({top: '+=10px'}, 'fast');
            break;
        case 68: //D
            $(this).animate({left: '+=10px'}, 'fast');
            break;
        default:
            break;
    }
});
$(document).click( function() {
    // if(key.which == 13)
    {
        var $toadd = "<div class='";
        switch($index % 4)
        {
            case 0:
                $toadd += "red' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 1:
                $toadd += "green' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 2:
                $toadd += "blue' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 3:
                $toadd += "yellow' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            default:
                break;
        }
        $('body').append($toadd);
        // $('body').on('click keydown','div', function() {
        //     $('body').append($toadd);
        // });
    }
});
});
Currently, the DIVs are added by clicking the page, but cant be moved using WASD. The s are focusable for the animate function to work. If I remove the dynamically adding by clicking and place a few static s, it works great.
Thanks for anything you can offer!
 
    