bootstrap popover add esc keypress check and close

Go To StackoverFlow.com

2

I am trying to extend bootstrap popover to close on escape on manual mode. I am trying to extend the tooltip class which the popover class inherts like the below:

/* WHY CANT I CALL the HIDE FUNCTION WHEN ESC key press is intercepted????

   Why is the hide class undefined when the keypress is intercetped?
*/

!function ($) {

    "use strict"

    /* TOOLTIP PUBLIC CLASS DEFINITION
    * =============================== */

    var Tooltip = function (element, options) {
        this.init('tooltip', element, options)
    }

    Tooltip.prototype = {

        constructor: Tooltip

  , init: function (type, element, options) {
      //init logic here

      $(document).keypress(function (e) {
          if (e.which == 27) { this.hide };  
      });                    ^^^^^^^^^^^^^
                             this.hide is undefined on debug????
  }

  , hide: function () {
     //hide logic
  }
}
2012-04-04 00:39
by River


4

You need to use this:

$tooltip = this;
$(document).keydown(function(e){
   if (e.keyCode === 27)
      $tooltip.hide();
});

Your problem is that the "this" you want is actually the document and it doesn't have a hide function. When the keypress/keydown event is triggered the "this" inside the function is the element the event was fired on therefore the document. Remember JavaScript has function scope which means you need to be cautious about your "this" variables when inside many different functions.

2012-04-04 01:22
by cha55son
Ads