Implementing keyboard control with jQuery draggable
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
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 } |
No Comments