0

I've modified bootstrap's popover function to include a callback which works great. But in the callback I cannot programmatically focus on the first form field. Strange, because I can manipulate other elements in the callback function as well as focus on the element at other points.

Here's the code to add a callback which I got from another SO question (https://stackoverflow.com/a/14727204/1596547):

var tmp = $.fn.popover.Constructor.prototype.show;
$.fn.popover.Constructor.prototype.show = function () {
  tmp.call(this);
  if (this.options.callback) {
    this.options.callback();
  }
}

Here's the popover code:

$('#a-editor-btn').popover({
    html: true,     
    placement: 'bottom',
    callback: function(){
        $('#a-form-point').focus();  //nothing happens
        console.log('hello');  // works
    .
    .

    },
    content: $('#a-form').html()
}).parent().delegate('button#insert-point-btn', 'click', function() {
    insertPoint();
}).delegate('.a-form','keypress', function(e) {
    if ( e.which == 13 ) {
        insertPoint();
    }
});
Community
  • 1
  • 1
mozgras
  • 3,215
  • 3
  • 21
  • 17
  • In lack of HTML / CSS, it seems to me that you are trying to focus an invisible field, that you cant do. focus() is called before the content of the popover is instantiated. – davidkonrad Jul 01 '13 at 09:13
  • Thanks for your thought, the callback function is used so that the element is selected after it's instantiated. Strangely enough, the code is working now. I'll update if I can figure out why. – mozgras Jul 01 '13 at 16:42

1 Answers1

1

Your button click seems to submit the form. After submitting your focus is lost. Prevent submitting by adding .click(function(){return false;}); after your .popover().

    $('#a-editor-btn').popover({
    html: true,     
    placement: 'bottom',
    callback: function(){
        //e.stopPropagation();
        thisfocus();  //nothing happens
        console.log('hello');  // works

    },
    content: $('#a-form').html()
}).parent().delegate('button#insert-point-btn', 'click', function() {
    insertPoint();
}).delegate('.a-form','keypress', function(e) {
    if ( e.which == 13 ) {
        insertPoint();
    }
}).click(function(){return false;});    

Now you popover won't disappear any more. Quick fix: call the hide() with a timeout:

var tmp = $.fn.popover.Constructor.prototype.show;
var tmp2 = $.fn.popover.Constructor.prototype.hide;
$.fn.popover.Constructor.prototype.show = function () {
  tmp.call(this);
  if (this.options.callback) {
    this.options.callback();
  }
   var that = this;
   setTimeout(function(){tmp2.call(that)},500); 
}       

See: http://bootply.com/66195

Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224