Skip to Content

SAPUI5 – Enable Keyboard Shortcuts

There are scenarios wherein the UI5 app should support keyboard shortcuts to perform some actions.

Here is a template that can be usedĀ as hook to write custom logic:

In your controller file, use the below method:

onInit : function() {
//after all the necessary code in init method
  this.setKeyboardShortcuts();
},

setKeyboardShortcuts: function(){
//here in this example, I have attached to 'document', you may attach to specific view or control
$(document).keydown($.proxy(function(evt) {
	switch(evt.keyCode){
		case 13: //enter key
// if enter key is pressed on checkbox control in ui5, default selection occurs, we need to undo this
                     var control = sap.ui.getCore().byId(evt.target.getAttribute('id'));
                     if (control && control.getMetadata().getName() == "sap.m.CheckBox" && control.getEnabled() && control.getEditable()) { //check if control is checkbox
                        //evt.preventDefault();
                        evt.stopImmediatePropagation();
                        control.setSelected(!control.getSelected());
                        control.fireSelect(new sap.ui.base.Event("customClick", control, {})); //checkbox SELECT event
                    }
//now call the actual event/method for the keyboard keypress
		   this.anyMethodThatShouldbeCalledUponEnterKeyHit();
		break;
			
                case 118: //F7 key
		     var control = this.byId("idPrevPageButton"); //or sap.ui.getCore().byId("idPrevPageButton")
	             if (control && control.getEnabled() && control.getEditable()) {
			control.firePress(); //button PRESS event
		     }
		     break;
                
//for other SHORTCUT cases: refer link1 - https://css-tricks.com/snippets/javascript/javascript-keycodes/   
                default: break;
	}, this));
},

 

2 Comments
You must be Logged on to comment or reply to a post.
  • Hi Venkatesh,

    How can I add view as you mentioned ?? doing it on document is creating errorĀ  on

    var control = this.byId("idPrevPageButton");

    because “this” is documnt here.

     

    Regards

    Rakesh