Handle keyboard hide and show events in ionic view

Posted By : Milind Ahuja | 09-Apr-2017

It is a very common issue in iOS when you have the keyboard up, and the part of your ionic view is not visible and not even scrollable. 

Unfortunately, iOS leaves this situation to the developers to handle. 

The best way to handle this is to use event listener method that fires when user clicks a button, in our case when keyboard is visible or not visible. The addEventListener() method attaches an event handler to the particular element specified by the developer.

These events then can be used by css and angular directive ng-class to manager the height of the ionic view.

Following is the code to make you understand it better:

CONTROLLER:

      $scope.isKeyboardOpen = false;

     //Event that fires when the keyboard is up.
        window.addEventListener('native.keyboardshow', keyboardShowHandler);
        function keyboardShowHandler(e){
            $scope.isKeyboardOpen = true;
            //console.log('Keyboard height is ' + e.keyboardHeight);
        }
        
		//Event that fires when the keyboard is not visible.
        window.addEventListener('native.keyboardhide', keyboardHideHandler);
        function keyboardHideHandler(e){
            $scope.isKeyboardOpen = false;
            //console.log('Keyboard height is:::::::: ' + e.keyboardHeight);
        }
  

Variable for keyboard show/hide which is false initially as the keyboard is hidden. As soon as the keyboard pops up, the variable becomes true.

Now, this variable is used in HTML to apply css class according to the keyboard to adjust the height of ionic view.

HTML:

     

YOUR CONTENT...

CSS:

      /*this class will be added when keyboard opens up*/
      .custom-height-dashboard{
         bottom: 258px !important;
      }
   

Now, your ionic view adjusts itself and moves up/down accordingly.

 

THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..