mozgras
mozgras

Reputation: 3325

Twitter's Bootstrap 2.x popover callback can't focus on element

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();
    }
});

Upvotes: 0

Views: 444

Answers (1)

Bass Jobsen
Bass Jobsen

Reputation: 49044

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

Upvotes: 1

Related Questions