Skip to content
The Web Fosters: ideas into reality
Menu

Implementing keyboard control with jQuery draggable

10 April 2018, by Nikhil Agrawal

Written in 2018. Versions and links mentioned here may be out of date.

jQuery Draggable with keyboard controls

In one of our recent project, we need to implement jQuery draggable with keyboard control.

jQuery draggable is a good option to move element using mouse in users interface. But it lacks the functionality of keyboard control.

But it can be easily achieved using keyup & keydown events.

jQuery('div#draggable').draggable({

	create: function(event, ui) {

		jQuery(document).on('keydown', function(e){

            switch(e.which) {
                case 37: {
                    e.preventDefault(); //Prevent default action for keys
                    console.log("left");

                    //Adjust the css position.
                    jQuery(this).css('left', parseFloat(jQuery(this).css('left')) - 1 + 'px');
                    break;
                }
                case 38: {
                    e.preventDefault();
                    console.log("up");
                    jQuery(this).css('top', parseFloat(jQuery(this).css('top')) - 1 + 'px');
                    break;
                }
                case 39: {
                    e.preventDefault();
                    console.log("right");
                    jQuery(this).css('left', parseFloat(jQuery(this).css('left')) + 1 + 'px');
                    break;
                }
                case 40: {
                    e.preventDefault();
                    console.log("down");
                    jQuery(this).css('top', parseFloat(jQuery(this).css('top')) + 1 + 'px');
                    break;
                }
            }
        }).on('keyup', function(e){
            var key = e.which;
            if(key == 37 || key == 38 || key == 39 || key == 40){
                //Perfome the same operatin which you on stop of draggable.
                update_div_coordinates(jQuery(this));
            }
        });
	},

    stop: function( event, ui ) {

    	update_div_coordinates(jQuery(this));
    }
});

function destroy_draggable(){
	jQuery('div#draggable').draggable( "destroy" );
	jQuery(document).off('keydown');
    jQuery(document).off('keyup');
}

function update_div_coordinates(element){
	//logic
}