10 April 2018 in Uncategorized
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. JavaScript 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 } 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 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}