Tooltip/Popover should reposition itself automatically when window is resized or otherwise
See original GitHub issueUsing Bootstrap in a client project, I had to fix a bug where a Popover was incorrectly positioned. The detail was that the mix of markup and JavaScript on the page created the popover, set the focus to the triggering field (causing the Popover to appear), but then other JavaScript modified the DOM (adding an alert to the top of the page) that shifted down the triggering field … and the Popover stayed positioned relative to the fields original position.
I also noticed that resizing the browser window also fails to reposition the Popover when, again, the location of the underlying field has changed.
My brief research on DOM events indicates that support for generic DOM tree modification events is spotty and buggy, but handling the window resize event would be sufficient for many people.
My approach to this is a bit of a hack (and has some Apache Tapestry details mixed in).
/** Adds a new operation, "reposition", to Bootstrap's popover that
* re-positions the tooltip/popover if it is currently visible. This is used to handle
* changes to the DOM and window resizing.
*/
jQuery.fn.popover.Constructor.prototype.reposition = function () {
if (this.enabled && this.tip().hasClass("in")) {
this.show();
}
}
… and in the code that creates the Popover:
matches.popover(options);
function doReposition() {
matches.popover("reposition");
}
jQuery(window).resize(_.throttle(doReposition, 250));
// Ideally, there would just be a way to handle this for anything that modifies the DOM.
T5.sub(T5.events.ADD_ALERT, null, doReposition);
This works acceptibly; there’s a slighe fade in/fade out animation here that I’d prefer to avoid; it would be nice if the tooltip show() function could be broken up a little, so that the code that determines position could be invoked directly, without all the other stuff that show() does.
Issue Analytics
- State:
- Created 11 years ago
- Comments:11 (4 by maintainers)
Top GitHub Comments
Because of the location of the item that displays the tooltip I really needed something that that could recalculate the tooltip’s position. I do think that @hlship is absolutely right about this being broken up in the
show
function. I took theshow
function and eliminated everything that I thought was not needed for a recalc.Here is what I have:
Using this I was able to then call the following anywhere in my code to recalculate the tooltip’s position
With that you can attach it to event listeners, etc. I hope this helps someone. I couldn’t use this
show
function since it triggered the transition animation. This in my mind was a better solution.As for popovers, I’m sure this could be adapted for it.
Another hack/workaround (avoiding CSS transitions during resize):
CSS: