Replace Popper.js with CSS Anchor Positioning API

BREAKING CHANGE: Popper.js is no longer a dependency. Dropdowns, tooltips,
and popovers now use native CSS Anchor Positioning with a polyfill fallback.

JavaScript:
- Add positioning.js utility with responsive placement support
- Rewrite dropdown.js to use anchor positioning and popover attribute
- Rewrite tooltip.js to use anchor positioning
- Update popover.js with data-api click handler
- Remove Popper.js imports and configuration options
- Add responsive placement syntax (e.g., "bottom md:top lg:right-start")

SCSS:
- Add _anchor-positioning.scss with base styles for positioned elements
- Update dropdown, tooltip, and popover styles for anchor positioning
- Add b-dropdown custom element support

Package:
- Replace @popperjs/core with @oddbird/css-anchor-positioning (optional polyfill)

Docs:
- Update dropdowns, tooltips, and popovers documentation
This commit is contained in:
Mark Otto 2025-12-11 09:47:57 -08:00
parent 39edb8da1c
commit b2fd7011c3
20 changed files with 1812 additions and 1233 deletions

View File

@ -9,6 +9,7 @@ export { default as Alert } from './src/alert.js'
export { default as Button } from './src/button.js'
export { default as Carousel } from './src/carousel.js'
export { default as Collapse } from './src/collapse.js'
export { default as Dialog } from './src/dialog.js'
export { default as Dropdown } from './src/dropdown.js'
export { default as Modal } from './src/modal.js'
export { default as Offcanvas } from './src/offcanvas.js'

View File

@ -9,6 +9,7 @@ import Alert from './src/alert.js'
import Button from './src/button.js'
import Carousel from './src/carousel.js'
import Collapse from './src/collapse.js'
import Dialog from './src/dialog.js'
import Dropdown from './src/dropdown.js'
import Modal from './src/modal.js'
import Offcanvas from './src/offcanvas.js'
@ -23,6 +24,7 @@ export default {
Button,
Carousel,
Collapse,
Dialog,
Dropdown,
Modal,
Offcanvas,

View File

@ -5,21 +5,32 @@
* --------------------------------------------------------------------------
*/
import * as Popper from '@popperjs/core'
import BaseComponent from './base-component.js'
import EventHandler from './dom/event-handler.js'
import Manipulator from './dom/manipulator.js'
import SelectorEngine from './dom/selector-engine.js'
import {
execute,
getElement,
getNextActiveElement,
getUID,
isDisabled,
isElement,
isRTL,
isVisible,
noop
} from './util/index.js'
import {
applyAnchorStyles,
applyPositionedStyles,
BreakpointObserver,
generateAnchorName,
getPlacementForViewport,
isResponsivePlacement,
parseResponsivePlacement,
removePositioningStyles,
supportsAnchorPositioning,
supportsPopover
} from './util/positioning.js'
/**
* Constants
@ -57,7 +68,10 @@ const SELECTOR_MENU = '.dropdown-menu'
const SELECTOR_NAVBAR = '.navbar'
const SELECTOR_NAVBAR_NAV = '.navbar-nav'
const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'
const SELECTOR_DROPDOWN_CONTAINER = 'b-dropdown'
const SELECTOR_STICKY_FIXED = '.sticky-top, .sticky-bottom, .fixed-top, .fixed-bottom'
// Placement mappings for anchor positioning
const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'
const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end'
const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start'
@ -69,19 +83,15 @@ const PLACEMENT_BOTTOMCENTER = 'bottom'
const Default = {
autoClose: true,
boundary: 'clippingParents',
display: 'dynamic',
offset: [0, 2],
popperConfig: null,
reference: 'toggle'
}
const DefaultType = {
autoClose: '(boolean|string)',
boundary: '(string|element)',
display: 'string',
offset: '(array|string|function)',
popperConfig: '(null|object|function)',
reference: '(string|element|object)'
}
@ -93,13 +103,37 @@ class Dropdown extends BaseComponent {
constructor(element, config) {
super(element, config)
this._popper = null
this._parent = this._element.parentNode // dropdown wrapper
// TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/
this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] ||
SelectorEngine.prev(this._element, SELECTOR_MENU)[0] ||
SelectorEngine.findOne(SELECTOR_MENU, this._parent)
this._parent = this._element.closest(SELECTOR_DROPDOWN_CONTAINER) || this._element.parentNode
// Find menu via data-bs-target, or fallback to DOM traversal
const target = this._element.getAttribute('data-bs-target')
if (target) {
this._menu = SelectorEngine.findOne(target)
} else {
// Look for menu in <b-dropdown> wrapper first, then fallback to sibling/parent search
const container = this._element.closest(SELECTOR_DROPDOWN_CONTAINER)
if (container) {
this._menu = SelectorEngine.findOne(SELECTOR_MENU, container)
}
if (!this._menu) {
this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] ||
SelectorEngine.prev(this._element, SELECTOR_MENU)[0] ||
SelectorEngine.findOne(SELECTOR_MENU, this._parent)
}
}
this._inNavbar = this._detectNavbar()
this._inStickyContext = this._detectStickyContext()
this._anchorName = null
this._breakpointObserver = null
this._responsivePlacements = null
// Set up popover attribute for auto-dismiss behavior
this._setupPopoverAttribute()
// Parse responsive placement if present
this._setupResponsivePlacement()
}
// Getters
@ -135,7 +169,8 @@ class Dropdown extends BaseComponent {
return
}
this._createPopper()
// Set up native anchor positioning
this._setupPositioning()
// If this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
@ -150,6 +185,11 @@ class Dropdown extends BaseComponent {
this._element.focus()
this._element.setAttribute('aria-expanded', true)
// Show using Popover API if supported
if (supportsPopover() && this._menu.hasAttribute('popover')) {
this._menu.showPopover()
}
this._menu.classList.add(CLASS_NAME_SHOW)
this._element.classList.add(CLASS_NAME_SHOW)
EventHandler.trigger(this._element, EVENT_SHOWN, relatedTarget)
@ -168,17 +208,21 @@ class Dropdown extends BaseComponent {
}
dispose() {
if (this._popper) {
this._popper.destroy()
if (this._breakpointObserver) {
this._breakpointObserver.dispose()
this._breakpointObserver = null
}
this._cleanupPositioning()
super.dispose()
}
update() {
this._inNavbar = this._detectNavbar()
if (this._popper) {
this._popper.update()
// With native anchor positioning, updates happen automatically
// Re-apply positioning if needed
if (this._isShown()) {
this._setupPositioning()
}
}
@ -197,14 +241,22 @@ class Dropdown extends BaseComponent {
}
}
if (this._popper) {
this._popper.destroy()
// Hide using Popover API if supported
if (supportsPopover() && this._menu.hasAttribute('popover')) {
try {
this._menu.hidePopover()
} catch {
// Already hidden
}
}
// Clean up positioning
this._cleanupPositioning()
this._menu.classList.remove(CLASS_NAME_SHOW)
this._element.classList.remove(CLASS_NAME_SHOW)
this._element.setAttribute('aria-expanded', 'false')
Manipulator.removeDataAttribute(this._menu, 'popper')
Manipulator.removeDataAttribute(this._menu, 'popper') // Legacy cleanup
EventHandler.trigger(this._element, EVENT_HIDDEN, relatedTarget)
}
@ -214,37 +266,128 @@ class Dropdown extends BaseComponent {
if (typeof config.reference === 'object' && !isElement(config.reference) &&
typeof config.reference.getBoundingClientRect !== 'function'
) {
// Popper virtual elements require a getBoundingClientRect method
throw new TypeError(`${NAME.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`)
}
return config
}
_createPopper() {
if (typeof Popper === 'undefined') {
throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org/docs/v2/)')
_setupPopoverAttribute() {
// Use popover="auto" for automatic light-dismiss behavior when autoClose is true
// Use popover="manual" when autoClose is false or specific
if (supportsPopover()) {
if (this._config.autoClose === true) {
this._menu.setAttribute('popover', 'auto')
} else {
this._menu.setAttribute('popover', 'manual')
}
}
}
_setupPositioning() {
// Skip positioning for static display
if (this._config.display === 'static') {
Manipulator.setDataAttribute(this._menu, 'popper', 'static') // Legacy attribute
return
}
let referenceElement = this._element
// Get placement for data attribute (used by CSS for styling)
const placement = this._getPlacement()
if (this._config.reference === 'parent') {
referenceElement = this._parent
} else if (isElement(this._config.reference)) {
referenceElement = getElement(this._config.reference)
} else if (typeof this._config.reference === 'object') {
referenceElement = this._config.reference
// For sticky/fixed contexts (like sticky navbars), skip anchor positioning
// to avoid jitter during scroll. CSS handles positioning via absolute.
if (this._inStickyContext) {
this._menu.dataset.bsPlacement = placement
return
}
const popperConfig = this._getPopperConfig()
this._popper = Popper.createPopper(referenceElement, this._menu, popperConfig)
// Check if native anchor positioning is supported
if (supportsAnchorPositioning()) {
// Generate unique anchor name
const uid = getUID(NAME)
this._anchorName = generateAnchorName(NAME, uid)
// Determine reference element
let referenceElement = this._element
if (this._config.reference === 'parent') {
referenceElement = this._parent
} else if (isElement(this._config.reference)) {
referenceElement = getElement(this._config.reference)
} else if (typeof this._config.reference === 'object') {
// Virtual element - for backward compatibility
// Native anchor positioning doesn't support virtual elements directly
// Fall back to toggle element
referenceElement = this._element
}
// Apply anchor to reference element
applyAnchorStyles(referenceElement, this._anchorName)
// Get offset
const offset = this._getOffset()
// Apply positioning to menu
applyPositionedStyles(this._menu, {
anchorName: this._anchorName,
placement,
offset,
fallbackPlacements: ['top', 'bottom', 'left', 'right']
})
} else {
// Fallback: Use data attribute for CSS-based positioning
// The CSS in _dropdown.scss handles positioning via [data-bs-placement]
this._menu.dataset.bsPlacement = placement
}
}
_cleanupPositioning() {
if (this._anchorName) {
// Get reference element
let referenceElement = this._element
if (this._config.reference === 'parent') {
referenceElement = this._parent
} else if (isElement(this._config.reference)) {
referenceElement = getElement(this._config.reference)
}
removePositioningStyles(referenceElement, this._menu)
this._anchorName = null
}
}
_isShown() {
return this._menu.classList.contains(CLASS_NAME_SHOW)
}
_setupResponsivePlacement() {
const placementAttr = this._element.getAttribute('data-bs-placement')
if (placementAttr && isResponsivePlacement(placementAttr)) {
this._responsivePlacements = parseResponsivePlacement(placementAttr)
// Set up breakpoint observer to update positioning on resize
this._breakpointObserver = new BreakpointObserver(() => {
if (this._isShown()) {
this._setupPositioning()
}
})
}
}
_getPlacement() {
// Check for responsive placements first
if (this._responsivePlacements) {
return getPlacementForViewport(this._responsivePlacements)
}
// Check for explicit data-bs-placement on the toggle (non-responsive)
const explicitPlacement = this._element.getAttribute('data-bs-placement')
if (explicitPlacement) {
return explicitPlacement
}
// Fall back to wrapper class approach for backward compatibility
const parentDropdown = this._parent
if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {
@ -277,6 +420,10 @@ class Dropdown extends BaseComponent {
return this._element.closest(SELECTOR_NAVBAR) !== null
}
_detectStickyContext() {
return this._element.closest(SELECTOR_STICKY_FIXED) !== null
}
_getOffset() {
const { offset } = this._config
@ -285,44 +432,12 @@ class Dropdown extends BaseComponent {
}
if (typeof offset === 'function') {
return popperData => offset(popperData, this._element)
return offset({}, this._element)
}
return offset
}
_getPopperConfig() {
const defaultBsPopperConfig = {
placement: this._getPlacement(),
modifiers: [{
name: 'preventOverflow',
options: {
boundary: this._config.boundary
}
},
{
name: 'offset',
options: {
offset: this._getOffset()
}
}]
}
// Disable Popper if we have a static display or Dropdown is in Navbar
if (this._inNavbar || this._config.display === 'static') {
Manipulator.setDataAttribute(this._menu, 'popper', 'static') // TODO: v6 remove
defaultBsPopperConfig.modifiers = [{
name: 'applyStyles',
enabled: false
}]
}
return {
...defaultBsPopperConfig,
...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig])
}
}
_selectMenuItem({ key, target }) {
const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element))

View File

@ -5,6 +5,7 @@
* --------------------------------------------------------------------------
*/
import EventHandler from './dom/event-handler.js'
import Tooltip from './tooltip.js'
/**
@ -19,7 +20,7 @@ const SELECTOR_CONTENT = '.popover-body'
const Default = {
...Tooltip.Default,
content: '',
offset: [0, 8],
offset: [8, 8],
placement: 'right',
template: '<div class="popover" role="tooltip">' +
'<div class="popover-arrow"></div>' +
@ -68,6 +69,23 @@ class Popover extends Tooltip {
_getContent() {
return this._resolvePossibleFunction(this._config.content)
}
// Static
static dataApiClickHandler(event) {
const popover = Popover.getOrCreateInstance(event.target)
popover.toggle()
}
}
/**
* Data API implementation
* Lazily initialize popovers on first interaction
*/
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="popover"]'
const DATA_API_KEY = '.data-api'
const EVENT_CLICK_DATA_API = `click${DATA_API_KEY}`
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, Popover.dataApiClickHandler)
export default Popover

View File

@ -5,15 +5,25 @@
* --------------------------------------------------------------------------
*/
import * as Popper from '@popperjs/core'
import BaseComponent from './base-component.js'
import EventHandler from './dom/event-handler.js'
import Manipulator from './dom/manipulator.js'
import {
execute, findShadowRoot, getElement, getUID, isRTL, noop
execute, findShadowRoot, getUID, isRTL, noop
} from './util/index.js'
import { DefaultAllowlist } from './util/sanitizer.js'
import TemplateFactory from './util/template-factory.js'
import {
applyAnchorStyles,
applyPositionedStyles,
BreakpointObserver,
generateAnchorName,
getPlacementForViewport,
isResponsivePlacement,
parseResponsivePlacement,
removePositioningStyles,
supportsPopover
} from './util/positioning.js'
/**
* Constants
@ -58,15 +68,12 @@ const AttachmentMap = {
const Default = {
allowList: DefaultAllowlist,
animation: true,
boundary: 'clippingParents',
container: false,
customClass: '',
delay: 0,
fallbackPlacements: ['top', 'right', 'bottom', 'left'],
html: false,
offset: [0, 6],
placement: 'top',
popperConfig: null,
sanitize: true,
sanitizeFn: null,
selector: false,
@ -81,15 +88,12 @@ const Default = {
const DefaultType = {
allowList: 'object',
animation: 'boolean',
boundary: '(string|element)',
container: '(string|element|boolean)',
customClass: '(string|function)',
delay: '(number|object)',
fallbackPlacements: 'array',
html: 'boolean',
offset: '(array|string|function)',
placement: '(string|function)',
popperConfig: '(null|object|function)',
sanitize: 'boolean',
sanitizeFn: '(null|function)',
selector: '(string|boolean)',
@ -104,10 +108,6 @@ const DefaultType = {
class Tooltip extends BaseComponent {
constructor(element, config) {
if (typeof Popper === 'undefined') {
throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org/docs/v2/)')
}
super(element, config)
// Private
@ -115,9 +115,11 @@ class Tooltip extends BaseComponent {
this._timeout = 0
this._isHovered = null
this._activeTrigger = {}
this._popper = null
this._templateFactory = null
this._newContent = null
this._anchorName = null
this._breakpointObserver = null
this._responsivePlacements = null
// Protected
this.tip = null
@ -127,6 +129,9 @@ class Tooltip extends BaseComponent {
if (!this._config.selector) {
this._fixTitle()
}
// Parse responsive placement if present
this._setupResponsivePlacement()
}
// Getters
@ -171,13 +176,18 @@ class Tooltip extends BaseComponent {
dispose() {
clearTimeout(this._timeout)
if (this._breakpointObserver) {
this._breakpointObserver.dispose()
this._breakpointObserver = null
}
EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler)
if (this._element.getAttribute('data-bs-original-title')) {
this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title'))
}
this._disposePopper()
this._disposeTooltip()
super.dispose()
}
@ -198,21 +208,25 @@ class Tooltip extends BaseComponent {
return
}
// TODO: v6 remove this or make it optional
this._disposePopper()
// Clean up any existing tooltip
this._disposeTooltip()
const tip = this._getTipElement()
this._element.setAttribute('aria-describedby', tip.getAttribute('id'))
const { container } = this._config
if (!this._element.ownerDocument.documentElement.contains(this.tip)) {
container.append(tip)
document.body.append(tip)
EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED))
}
this._popper = this._createPopper(tip)
// Set up native anchor positioning
this._setupPositioning(tip)
// Show using Popover API if supported, otherwise just add class
if (supportsPopover() && tip.popover !== undefined) {
tip.showPopover()
}
tip.classList.add(CLASS_NAME_SHOW)
@ -252,6 +266,15 @@ class Tooltip extends BaseComponent {
const tip = this._getTipElement()
tip.classList.remove(CLASS_NAME_SHOW)
// Hide using Popover API if supported
if (supportsPopover() && tip.popover !== undefined) {
try {
tip.hidePopover()
} catch {
// Popover might already be hidden
}
}
// If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
@ -271,7 +294,7 @@ class Tooltip extends BaseComponent {
}
if (!this._isHovered) {
this._disposePopper()
this._disposeTooltip()
}
this._element.removeAttribute('aria-describedby')
@ -282,8 +305,10 @@ class Tooltip extends BaseComponent {
}
update() {
if (this._popper) {
this._popper.update()
// With native anchor positioning, the browser handles updates automatically
// This method is kept for API compatibility
if (this.tip && this._anchorName) {
this._setupPositioning(this.tip)
}
}
@ -303,13 +328,11 @@ class Tooltip extends BaseComponent {
_createTipElement(content) {
const tip = this._getTemplateFactory(content).toHtml()
// TODO: remove this check in v6
if (!tip) {
return null
}
tip.classList.remove(CLASS_NAME_FADE, CLASS_NAME_SHOW)
// TODO: v6 the following can be achieved with CSS only
tip.classList.add(`bs-${this.constructor.NAME}-auto`)
const tipId = getUID(this.constructor.NAME).toString()
@ -320,13 +343,18 @@ class Tooltip extends BaseComponent {
tip.classList.add(CLASS_NAME_FADE)
}
// Set up for Popover API - use 'manual' for programmatic control
if (supportsPopover()) {
tip.setAttribute('popover', 'manual')
}
return tip
}
setContent(content) {
this._newContent = content
if (this._isShown()) {
this._disposePopper()
this._disposeTooltip()
this.show()
}
}
@ -370,10 +398,51 @@ class Tooltip extends BaseComponent {
return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW)
}
_createPopper(tip) {
const placement = execute(this._config.placement, [this, tip, this._element])
const attachment = AttachmentMap[placement.toUpperCase()]
return Popper.createPopper(this._element, tip, this._getPopperConfig(attachment))
_setupResponsivePlacement() {
const placement = this._config.placement
// Only set up responsive observer if placement is a string with breakpoint syntax
if (typeof placement === 'string' && isResponsivePlacement(placement)) {
this._responsivePlacements = parseResponsivePlacement(placement)
// Set up breakpoint observer to update positioning on resize
this._breakpointObserver = new BreakpointObserver(() => {
if (this._isShown()) {
this._setupPositioning(this.tip)
}
})
}
}
_setupPositioning(tip) {
let placement
// Check for responsive placements first
if (this._responsivePlacements) {
placement = getPlacementForViewport(this._responsivePlacements)
} else {
placement = execute(this._config.placement, [this, tip, this._element])
}
const attachment = AttachmentMap[placement.toUpperCase()] || placement
// Generate unique anchor name
const uid = getUID(this.constructor.NAME)
this._anchorName = generateAnchorName(this.constructor.NAME, uid)
// Apply anchor to trigger element
applyAnchorStyles(this._element, this._anchorName)
// Get offset
const offset = this._getOffset()
// Apply positioning to tooltip
applyPositionedStyles(tip, {
anchorName: this._anchorName,
placement: attachment,
offset,
fallbackPlacements: this._config.fallbackPlacements
})
}
_getOffset() {
@ -384,7 +453,8 @@ class Tooltip extends BaseComponent {
}
if (typeof offset === 'function') {
return popperData => offset(popperData, this._element)
// For function offsets, call with element context
return offset({}, this._element)
}
return offset
@ -394,53 +464,6 @@ class Tooltip extends BaseComponent {
return execute(arg, [this._element, this._element])
}
_getPopperConfig(attachment) {
const defaultBsPopperConfig = {
placement: attachment,
modifiers: [
{
name: 'flip',
options: {
fallbackPlacements: this._config.fallbackPlacements
}
},
{
name: 'offset',
options: {
offset: this._getOffset()
}
},
{
name: 'preventOverflow',
options: {
boundary: this._config.boundary
}
},
{
name: 'arrow',
options: {
element: `.${this.constructor.NAME}-arrow`
}
},
{
name: 'preSetPlacement',
enabled: true,
phase: 'beforeMain',
fn: data => {
// Pre-set Popper's placement attribute in order to read the arrow sizes properly.
// Otherwise, Popper mixes up the width and height dimensions since the initial arrow style is for top placement
this._getTipElement().setAttribute('data-popper-placement', data.state.placement)
}
}
]
}
return {
...defaultBsPopperConfig,
...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig])
}
}
_setListeners() {
const triggers = this._config.trigger.split(' ')
@ -556,8 +579,6 @@ class Tooltip extends BaseComponent {
}
_configAfterMerge(config) {
config.container = config.container === false ? document.body : getElement(config.container)
if (typeof config.delay === 'number') {
config.delay = {
show: config.delay,
@ -588,22 +609,53 @@ class Tooltip extends BaseComponent {
config.selector = false
config.trigger = 'manual'
// In the future can be replaced with:
// const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]])
// `Object.fromEntries(keysWithDifferentValues)`
return config
}
_disposePopper() {
if (this._popper) {
this._popper.destroy()
this._popper = null
}
_disposeTooltip() {
if (this.tip) {
// Remove anchor positioning styles
removePositioningStyles(this._element, this.tip)
// Hide popover if using Popover API
if (supportsPopover() && this.tip.popover !== undefined) {
try {
this.tip.hidePopover()
} catch {
// Already hidden
}
}
this.tip.remove()
this.tip = null
}
this._anchorName = null
}
// Static
static dataApiHandler(event) {
const tooltip = Tooltip.getOrCreateInstance(event.target)
// For hover/focus triggers, manually trigger the enter/leave behavior
if (event.type === 'mouseenter' || event.type === 'focusin') {
tooltip._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true
tooltip._enter()
}
}
}
/**
* Data API implementation
* Lazily initialize tooltips on first interaction
*/
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="tooltip"]'
const DATA_API_KEY = '.data-api'
const EVENT_MOUSEENTER_DATA_API = `mouseenter${DATA_API_KEY}`
const EVENT_FOCUSIN_DATA_API = `focusin${DATA_API_KEY}`
EventHandler.on(document, EVENT_MOUSEENTER_DATA_API, SELECTOR_DATA_TOGGLE, Tooltip.dataApiHandler)
EventHandler.on(document, EVENT_FOCUSIN_DATA_API, SELECTOR_DATA_TOGGLE, Tooltip.dataApiHandler)
export default Tooltip

357
js/src/util/positioning.js Normal file
View File

@ -0,0 +1,357 @@
/**
* --------------------------------------------------------------------------
* Bootstrap util/positioning.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import { isRTL } from './index.js'
/**
* Bootstrap breakpoints (must match $grid-breakpoints in _config.scss)
* Order matters - from smallest to largest
*/
const BREAKPOINTS = {
xs: 0,
sm: 576,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536
}
const BREAKPOINT_ORDER = ['xs', 'sm', 'md', 'lg', 'xl', '2xl']
/**
* Parse a responsive placement string into breakpoint-specific placements
* Format: "placement bp:placement bp:placement"
* Example: "bottom md:top lg:right-start"
* @param {string} placementString - The placement string to parse
* @returns {object} Object mapping breakpoints to placements
*/
const parseResponsivePlacement = placementString => {
if (!placementString || typeof placementString !== 'string') {
return { xs: 'bottom' }
}
const placements = {}
const parts = placementString.trim().split(/\s+/)
for (const part of parts) {
if (part.includes(':')) {
// Breakpoint-prefixed placement (e.g., "md:top")
const [breakpoint, placement] = part.split(':')
if (BREAKPOINTS[breakpoint] !== undefined && placement) {
placements[breakpoint] = placement.toLowerCase()
}
} else {
// Default placement (applies to xs/base)
placements.xs = part.toLowerCase()
}
}
// Ensure we have at least a default
if (!placements.xs) {
placements.xs = 'bottom'
}
return placements
}
/**
* Get the effective placement for the current viewport width
* @param {object} responsivePlacements - Object mapping breakpoints to placements
* @param {number} [viewportWidth] - Current viewport width (defaults to window.innerWidth)
* @returns {string} The placement to use
*/
const getPlacementForViewport = (responsivePlacements, viewportWidth = window.innerWidth) => {
let effectivePlacement = responsivePlacements.xs || 'bottom'
// Walk through breakpoints in order and find the largest matching one
for (const breakpoint of BREAKPOINT_ORDER) {
const minWidth = BREAKPOINTS[breakpoint]
if (viewportWidth >= minWidth && responsivePlacements[breakpoint]) {
effectivePlacement = responsivePlacements[breakpoint]
}
}
return effectivePlacement
}
/**
* Check if a placement string contains responsive values
* @param {string} placementString - The placement string to check
* @returns {boolean} True if the string contains breakpoint prefixes
*/
const isResponsivePlacement = placementString => {
if (!placementString || typeof placementString !== 'string') {
return false
}
return placementString.includes(':')
}
/**
* Class to observe breakpoint changes and trigger callbacks
*/
class BreakpointObserver {
constructor(callback) {
this._callback = callback
this._mediaQueries = []
this._boundHandler = this._handleChange.bind(this)
this._init()
}
_init() {
// Create matchMedia listeners for each breakpoint
for (const breakpoint of BREAKPOINT_ORDER) {
const minWidth = BREAKPOINTS[breakpoint]
if (minWidth > 0) {
const mql = window.matchMedia(`(min-width: ${minWidth}px)`)
mql.addEventListener('change', this._boundHandler)
this._mediaQueries.push(mql)
}
}
}
_handleChange() {
this._callback()
}
dispose() {
for (const mql of this._mediaQueries) {
mql.removeEventListener('change', this._boundHandler)
}
this._mediaQueries = []
this._callback = null
}
}
/**
* Feature detection for native positioning APIs
*/
const supportsAnchorPositioning = () => {
try {
// Check for anchor-name support (core anchor positioning feature)
return CSS.supports('anchor-name', '--test')
} catch {
return false
}
}
/**
* Check if browser uses position-area (new spec) vs inset-area (old spec)
*/
const usesPositionArea = () => {
try {
return CSS.supports('position-area', 'block-end')
} catch {
return false
}
}
const supportsPopover = () => {
return typeof HTMLElement !== 'undefined' && 'popover' in HTMLElement.prototype
}
/**
* Placement mapping from Bootstrap placements to CSS anchor positioning inset-area values
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/inset-area
*/
const PLACEMENT_MAP = {
top: 'block-start',
'top-start': isRTL() ? 'block-start span-inline-start' : 'block-start span-inline-end',
'top-end': isRTL() ? 'block-start span-inline-end' : 'block-start span-inline-start',
bottom: 'block-end',
'bottom-start': isRTL() ? 'block-end span-inline-start' : 'block-end span-inline-end',
'bottom-end': isRTL() ? 'block-end span-inline-end' : 'block-end span-inline-start',
left: 'inline-start',
'left-start': 'inline-start span-block-end',
'left-end': 'inline-start span-block-start',
right: 'inline-end',
'right-start': 'inline-end span-block-end',
'right-end': 'inline-end span-block-start',
// Auto placement - let CSS handle fallbacks
auto: 'block-end'
}
/**
* Maps Bootstrap placement to CSS logical inset-area value
* @param {string} placement - Bootstrap placement (top, bottom, left, right, auto)
* @returns {string} CSS inset-area value
*/
const getInsetArea = placement => {
const normalizedPlacement = placement.toLowerCase()
return PLACEMENT_MAP[normalizedPlacement] || PLACEMENT_MAP.bottom
}
/**
* Maps Bootstrap fallback placements to position-try-fallbacks values
* @param {string[]} fallbacks - Array of Bootstrap placement strings
* @returns {string} CSS position-try-fallbacks value
*/
const getPositionTryFallbacks = fallbacks => {
if (!fallbacks || fallbacks.length === 0) {
return 'flip-block, flip-inline, flip-block flip-inline'
}
// Map each fallback to a position-try-fallbacks value
const mapped = fallbacks.map(placement => {
const normalized = placement.toLowerCase()
if (normalized.includes('top') || normalized.includes('bottom')) {
return 'flip-block'
}
if (normalized.includes('left') || normalized.includes('right')) {
return 'flip-inline'
}
return 'flip-block flip-inline'
})
// Remove duplicates and join
return [...new Set(mapped)].join(', ')
}
/**
* Generate a unique anchor name for positioning
* @param {string} prefix - Prefix for the anchor name
* @param {string|number} uid - Unique identifier
* @returns {string} CSS anchor name (e.g., "--bs-tooltip-123")
*/
const generateAnchorName = (prefix, uid) => {
return `--bs-${prefix}-anchor-${uid}`
}
/**
* Apply anchor positioning styles to an anchor element
* @param {HTMLElement} anchorElement - The element to anchor to
* @param {string} anchorName - The anchor name to use
*/
const applyAnchorStyles = (anchorElement, anchorName) => {
anchorElement.style.anchorName = anchorName
}
/**
* Apply positioned element styles using CSS anchor positioning
* @param {HTMLElement} positionedElement - The element to position
* @param {object} options - Positioning options
* @param {string} options.anchorName - The anchor name to position relative to
* @param {string} options.placement - Bootstrap placement string
* @param {number[]} options.offset - [x, y] offset values
* @param {string[]} options.fallbackPlacements - Fallback placements for auto-flip
*/
const applyPositionedStyles = (positionedElement, options) => {
const { anchorName, placement, offset = [0, 0], fallbackPlacements } = options
// Set position anchor
positionedElement.style.positionAnchor = anchorName
// Set position area based on placement
// Note: The spec renamed inset-area to position-area (Chrome 131+)
const areaValue = getInsetArea(placement)
if (usesPositionArea()) {
positionedElement.style.positionArea = areaValue
} else {
positionedElement.style.insetArea = areaValue
}
// Set position-try-fallbacks for auto-flipping
positionedElement.style.positionTryFallbacks = getPositionTryFallbacks(fallbackPlacements)
// Apply offsets using CSS custom properties
// Offset format: [skidding, distance] (same as Popper.js)
const [skidding, distance] = offset
if (skidding !== 0 || distance !== 0) {
positionedElement.style.setProperty('--bs-position-skidding', `${skidding}px`)
positionedElement.style.setProperty('--bs-position-distance', `${distance}px`)
}
// Store placement as data attribute for CSS styling hooks
positionedElement.dataset.bsPlacement = placement
}
/**
* Remove anchor positioning styles from elements
* @param {HTMLElement} anchorElement - The anchor element
* @param {HTMLElement} positionedElement - The positioned element
*/
const removePositioningStyles = (anchorElement, positionedElement) => {
if (anchorElement) {
anchorElement.style.anchorName = ''
}
if (positionedElement) {
positionedElement.style.positionAnchor = ''
positionedElement.style.positionArea = ''
positionedElement.style.insetArea = ''
positionedElement.style.positionTryFallbacks = ''
positionedElement.style.removeProperty('--bs-position-skidding')
positionedElement.style.removeProperty('--bs-position-distance')
delete positionedElement.dataset.bsPlacement
}
}
/**
* Get the current computed placement of a positioned element
* This is useful after CSS has applied fallback positioning
* @param {HTMLElement} positionedElement - The positioned element
* @returns {string} The current placement
*/
const getCurrentPlacement = positionedElement => {
// Try to get from data attribute first (what we set)
const setPlacement = positionedElement.dataset.bsPlacement
// In the future, we could potentially detect actual position via getComputedStyle
// For now, return what was set
return setPlacement || 'bottom'
}
/**
* Initialize the anchor positioning polyfill if needed
* @returns {Promise<boolean>} Whether polyfill was loaded
*/
const initPolyfill = async () => {
if (supportsAnchorPositioning()) {
return false
}
// Try to load the polyfill dynamically
try {
// Check if polyfill is already loaded
if (window.__CSS_ANCHOR_POLYFILL_LOADED__) {
return true
}
// The polyfill should be loaded via script tag or bundled
// This is a fallback for dynamic loading
const polyfill = await import('@oddbird/css-anchor-positioning')
if (polyfill && typeof polyfill.default === 'function') {
polyfill.default()
window.__CSS_ANCHOR_POLYFILL_LOADED__ = true
return true
}
} catch {
// Polyfill not available - positioning features may be limited in unsupported browsers
}
return false
}
export {
applyAnchorStyles,
applyPositionedStyles,
BreakpointObserver,
generateAnchorName,
getCurrentPlacement,
getInsetArea,
getPlacementForViewport,
getPositionTryFallbacks,
initPolyfill,
isResponsivePlacement,
parseResponsivePlacement,
removePositioningStyles,
supportsAnchorPositioning,
supportsPopover
}

View File

@ -82,7 +82,7 @@ describe('Dropdown', () => {
})
})
it('should create offset modifier correctly when offset option is a function', () => {
it('should create offset correctly when offset option is a function', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
@ -96,18 +96,14 @@ describe('Dropdown', () => {
const getOffset = jasmine.createSpy('getOffset').and.returnValue([10, 20])
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const dropdown = new Dropdown(btnDropdown, {
offset: getOffset,
popperConfig: {
onFirstUpdate(state) {
expect(getOffset).toHaveBeenCalledWith({
popper: state.rects.popper,
reference: state.rects.reference,
placement: state.placement
}, btnDropdown)
resolve()
}
}
offset: getOffset
})
btnDropdown.addEventListener('shown.bs.dropdown', () => {
expect(getOffset).toHaveBeenCalled()
resolve()
})
const offset = dropdown._getOffset()
expect(typeof offset).toEqual('function')
@ -132,7 +128,8 @@ describe('Dropdown', () => {
expect(dropdown._getOffset()).toEqual([10, 20])
})
it('should allow to pass config to Popper with `popperConfig`', () => {
// Note: popperConfig option is deprecated in favor of native CSS anchor positioning
it('should accept deprecated popperConfig option without error', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
@ -143,40 +140,15 @@ describe('Dropdown', () => {
].join('')
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
// Should not throw even with deprecated option
const dropdown = new Dropdown(btnDropdown, {
popperConfig: {
placement: 'left'
}
})
const popperConfig = dropdown._getPopperConfig()
expect(popperConfig.placement).toEqual('left')
})
it('should allow to pass config to Popper with `popperConfig` as a function', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-placement="right">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item" href="#">Secondary link</a>',
' </div>',
'</div>'
].join('')
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const getPopperConfig = jasmine.createSpy('getPopperConfig').and.returnValue({ placement: 'left' })
const dropdown = new Dropdown(btnDropdown, {
popperConfig: getPopperConfig
})
const popperConfig = dropdown._getPopperConfig()
// Ensure that the function was called with the default config.
expect(getPopperConfig).toHaveBeenCalledWith(jasmine.objectContaining({
placement: jasmine.any(String)
}))
expect(popperConfig.placement).toEqual('left')
expect(dropdown).toBeDefined()
})
})
@ -230,12 +202,12 @@ describe('Dropdown', () => {
firstDropdownEl.addEventListener('shown.bs.dropdown', () => {
expect(btnDropdown1).toHaveClass('show')
spyOn(dropdown1._popper, 'destroy')
btnDropdown2.click()
})
secondDropdownEl.addEventListener('shown.bs.dropdown', () => setTimeout(() => {
expect(dropdown1._popper.destroy).toHaveBeenCalled()
// First dropdown should be hidden when second one opens
expect(btnDropdown1).not.toHaveClass('show')
resolve()
}))
@ -508,59 +480,27 @@ describe('Dropdown', () => {
})
})
it('should toggle a dropdown with a valid virtual element reference', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle visually-hidden" data-bs-toggle="dropdown" aria-expanded="false">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item" href="#">Secondary link</a>',
' </div>',
'</div>'
].join('')
it('should throw error with invalid virtual element reference', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle visually-hidden" data-bs-toggle="dropdown" aria-expanded="false">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item" href="#">Secondary link</a>',
' </div>',
'</div>'
].join('')
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const virtualElement = {
nodeType: 1,
getBoundingClientRect() {
return {
width: 0,
height: 0,
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
expect(() => new Dropdown(btnDropdown, {
reference: {}
})).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.')
expect(() => new Dropdown(btnDropdown, {
reference: {
getBoundingClientRect: 'not-a-function'
}
expect(() => new Dropdown(btnDropdown, {
reference: {}
})).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.')
expect(() => new Dropdown(btnDropdown, {
reference: {
getBoundingClientRect: 'not-a-function'
}
})).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.')
// use onFirstUpdate as Poppers internal update is executed async
const dropdown = new Dropdown(btnDropdown, {
reference: virtualElement,
popperConfig: {
onFirstUpdate() {
expect(spy).toHaveBeenCalled()
expect(btnDropdown).toHaveClass('show')
expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true')
resolve()
}
}
})
const spy = spyOn(virtualElement, 'getBoundingClientRect').and.callThrough()
dropdown.toggle()
})
})).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.')
})
it('should not toggle a dropdown if the element is disabled', () => {
@ -854,12 +794,12 @@ describe('Dropdown', () => {
const dropdown = new Dropdown(btnDropdown)
btnDropdown.addEventListener('shown.bs.dropdown', () => {
spyOn(dropdown._popper, 'destroy')
dropdown.hide()
})
btnDropdown.addEventListener('hidden.bs.dropdown', () => {
expect(dropdown._popper.destroy).toHaveBeenCalled()
// Dropdown should be hidden
expect(btnDropdown).not.toHaveClass('show')
resolve()
})
@ -1033,7 +973,6 @@ describe('Dropdown', () => {
const dropdown = new Dropdown(btnDropdown)
expect(dropdown._popper).toBeNull()
expect(dropdown._menu).not.toBeNull()
expect(dropdown._element).not.toBeNull()
const spy = spyOn(EventHandler, 'off')
@ -1045,7 +984,7 @@ describe('Dropdown', () => {
expect(spy).toHaveBeenCalledWith(btnDropdown, Dropdown.EVENT_KEY)
})
it('should dispose dropdown with Popper', () => {
it('should dispose dropdown after showing', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
@ -1060,20 +999,18 @@ describe('Dropdown', () => {
dropdown.toggle()
expect(dropdown._popper).not.toBeNull()
expect(dropdown._menu).not.toBeNull()
expect(dropdown._element).not.toBeNull()
dropdown.dispose()
expect(dropdown._popper).toBeNull()
expect(dropdown._menu).toBeNull()
expect(dropdown._element).toBeNull()
})
})
describe('update', () => {
it('should call Popper and detect navbar on update', () => {
it('should detect navbar on update', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
@ -1088,18 +1025,14 @@ describe('Dropdown', () => {
dropdown.toggle()
expect(dropdown._popper).not.toBeNull()
const spyUpdate = spyOn(dropdown._popper, 'update')
const spyDetect = spyOn(dropdown, '_detectNavbar')
dropdown.update()
expect(spyUpdate).toHaveBeenCalled()
expect(spyDetect).toHaveBeenCalled()
})
it('should just detect navbar on update', () => {
it('should detect navbar even when not shown', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
@ -1116,7 +1049,6 @@ describe('Dropdown', () => {
dropdown.update()
expect(dropdown._popper).toBeNull()
expect(spy).toHaveBeenCalled()
})
})
@ -1165,7 +1097,7 @@ describe('Dropdown', () => {
})
})
it('should not use "static" Popper in navbar', () => {
it('should use static positioning in navbar', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = [
'<nav class="navbar navbar-expand-md bg-light">',
@ -1183,7 +1115,7 @@ describe('Dropdown', () => {
const dropdown = new Dropdown(btnDropdown)
btnDropdown.addEventListener('shown.bs.dropdown', () => {
expect(dropdown._popper).not.toBeNull()
// In navbar, positioning is static
expect(dropdownMenu.getAttribute('data-bs-popper')).toEqual('static')
resolve()
})
@ -1266,7 +1198,7 @@ describe('Dropdown', () => {
})
})
it('should not use Popper if display set to static', () => {
it('should use static display when configured', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
@ -1281,8 +1213,8 @@ describe('Dropdown', () => {
const dropdownMenu = fixtureEl.querySelector('.dropdown-menu')
btnDropdown.addEventListener('shown.bs.dropdown', () => {
// Popper adds this attribute when we use it
expect(dropdownMenu.getAttribute('data-popper-placement')).toBeNull()
// Static display uses data-bs-popper="static"
expect(dropdownMenu.getAttribute('data-bs-popper')).toEqual('static')
resolve()
})

View File

@ -114,24 +114,19 @@ describe('Tooltip', () => {
})
})
it('should create offset modifier when offset is passed as a function', () => {
it('should create offset when offset is passed as a function', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Offset from function"></a>'
const getOffset = jasmine.createSpy('getOffset').and.returnValue([10, 20])
const tooltipEl = fixtureEl.querySelector('a')
const tooltip = new Tooltip(tooltipEl, {
offset: getOffset,
popperConfig: {
onFirstUpdate(state) {
expect(getOffset).toHaveBeenCalledWith({
popper: state.rects.popper,
reference: state.rects.reference,
placement: state.placement
}, tooltipEl)
resolve()
}
}
offset: getOffset
})
tooltipEl.addEventListener('shown.bs.tooltip', () => {
expect(getOffset).toHaveBeenCalled()
resolve()
})
const offset = tooltip._getOffset()
@ -142,7 +137,7 @@ describe('Tooltip', () => {
})
})
it('should create offset modifier when offset option is passed in data attribute', () => {
it('should create offset when offset option is passed in data attribute', () => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip" data-bs-offset="10,20" title="Another tooltip"></a>'
const tooltipEl = fixtureEl.querySelector('a')
@ -151,39 +146,6 @@ describe('Tooltip', () => {
expect(tooltip._getOffset()).toEqual([10, 20])
})
it('should allow to pass config to Popper with `popperConfig`', () => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip"></a>'
const tooltipEl = fixtureEl.querySelector('a')
const tooltip = new Tooltip(tooltipEl, {
popperConfig: {
placement: 'left'
}
})
const popperConfig = tooltip._getPopperConfig('top')
expect(popperConfig.placement).toEqual('left')
})
it('should allow to pass config to Popper with `popperConfig` as a function', () => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip"></a>'
const tooltipEl = fixtureEl.querySelector('a')
const getPopperConfig = jasmine.createSpy('getPopperConfig').and.returnValue({ placement: 'left' })
const tooltip = new Tooltip(tooltipEl, {
popperConfig: getPopperConfig
})
const popperConfig = tooltip._getPopperConfig('top')
// Ensure that the function was called with the default config.
expect(getPopperConfig).toHaveBeenCalledWith(jasmine.objectContaining({
placement: jasmine.any(String)
}))
expect(popperConfig.placement).toEqual('left')
})
it('should use original title, if not "data-bs-title" is given', () => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Another tooltip"></a>'
@ -527,7 +489,8 @@ describe('Tooltip', () => {
tooltipEl.addEventListener('shown.bs.tooltip', () => {
expect(tooltip._getTipElement()).toHaveClass('bs-tooltip-auto')
expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('bottom')
// Native positioning uses data-bs-placement instead of data-popper-placement
expect(tooltip._getTipElement().getAttribute('data-bs-placement')).toEqual('bottom')
resolve()
})
@ -795,7 +758,7 @@ describe('Tooltip', () => {
it('should properly maintain tooltip state if leave event occurs and enter event occurs during hide transition', () => {
return new Promise(resolve => {
// Style this tooltip to give it plenty of room for popper to do what it wants
// Style this tooltip to give it plenty of room
fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Another tooltip" data-bs-placement="top" style="position:fixed;left:50%;top:50%;">Trigger</a>'
const tooltipEl = fixtureEl.querySelector('a')
@ -807,8 +770,8 @@ describe('Tooltip', () => {
})
setTimeout(() => {
expect(tooltip._popper).not.toBeNull()
expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('top')
// With native positioning, check data-bs-placement
expect(tooltip._getTipElement().getAttribute('data-bs-placement')).toEqual('top')
tooltipEl.dispatchEvent(createEvent('mouseout'))
setTimeout(() => {
@ -817,8 +780,7 @@ describe('Tooltip', () => {
}, 100)
setTimeout(() => {
expect(tooltip._popper).not.toBeNull()
expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('top')
expect(tooltip._getTipElement().getAttribute('data-bs-placement')).toEqual('top')
resolve()
}, 200)
}, 10)
@ -1032,7 +994,7 @@ describe('Tooltip', () => {
})
})
it('should not throw error running hide if popper hasn\'t been shown', () => {
it('should not throw error running hide if tooltip hasn\'t been shown', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
@ -1048,7 +1010,7 @@ describe('Tooltip', () => {
})
describe('update', () => {
it('should call popper update', () => {
it('should call update and not throw', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Another tooltip"></a>'
@ -1056,11 +1018,8 @@ describe('Tooltip', () => {
const tooltip = new Tooltip(tooltipEl)
tooltipEl.addEventListener('shown.bs.tooltip', () => {
const spy = spyOn(tooltip._popper, 'update')
tooltip.update()
expect(spy).toHaveBeenCalled()
// With native anchor positioning, update just re-applies positioning
expect(() => tooltip.update()).not.toThrow()
resolve()
})

View File

@ -0,0 +1,265 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../../../dist/css/bootstrap.min.css" rel="stylesheet">
<title>Responsive Placement</title>
<style>
.test-section {
min-height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
.breakpoint-indicator {
position: fixed;
top: 10px;
right: 10px;
padding: 8px 16px;
background: var(--bs-primary);
color: white;
border-radius: 4px;
font-weight: bold;
z-index: 9999;
}
</style>
</head>
<body>
<div class="breakpoint-indicator" id="breakpointIndicator">xs</div>
<div class="container py-4">
<h1>Responsive Placement <small class="text-secondary">Bootstrap Visual Test</small></h1>
<p class="lead">Test responsive placement syntax: <code>data-bs-placement="bottom md:top lg:right"</code></p>
<p>Resize your browser window to see placements change at different breakpoints.</p>
<hr class="my-4">
<h2>Dropdown Examples</h2>
<div class="test-section">
<div class="dropdown">
<button
class="btn btn-primary dropdown-toggle"
type="button"
data-bs-toggle="dropdown"
data-bs-placement="bottom-start md:top-start lg:right-start"
aria-expanded="false"
>
Responsive Dropdown
<small class="d-block text-white-50">bottom → md:top → lg:right</small>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</div>
</div>
<div class="row mt-4">
<div class="col-md-6">
<div class="test-section border rounded">
<div class="dropdown">
<button
class="btn btn-secondary dropdown-toggle"
type="button"
data-bs-toggle="dropdown"
data-bs-placement="bottom md:right xl:top"
aria-expanded="false"
>
bottom → md:right → xl:top
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
</ul>
</div>
</div>
</div>
<div class="col-md-6">
<div class="test-section border rounded">
<div class="dropdown">
<button
class="btn btn-secondary dropdown-toggle"
type="button"
data-bs-toggle="dropdown"
data-bs-placement="top sm:bottom lg:left"
aria-expanded="false"
>
top → sm:bottom → lg:left
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
</ul>
</div>
</div>
</div>
</div>
<hr class="my-4">
<h2>Tooltip Examples</h2>
<div class="test-section">
<button
type="button"
class="btn btn-info"
data-bs-toggle="tooltip"
data-bs-placement="top md:right lg:bottom"
data-bs-title="This tooltip changes position! top → md:right → lg:bottom"
>
Responsive Tooltip
</button>
</div>
<div class="row mt-4">
<div class="col-md-4 text-center">
<button
type="button"
class="btn btn-outline-secondary"
data-bs-toggle="tooltip"
data-bs-placement="bottom md:top"
data-bs-title="bottom → md:top"
>
bottom → md:top
</button>
</div>
<div class="col-md-4 text-center">
<button
type="button"
class="btn btn-outline-secondary"
data-bs-toggle="tooltip"
data-bs-placement="left lg:right"
data-bs-title="left → lg:right"
>
left → lg:right
</button>
</div>
<div class="col-md-4 text-center">
<button
type="button"
class="btn btn-outline-secondary"
data-bs-toggle="tooltip"
data-bs-placement="top sm:left md:bottom lg:right xl:top"
data-bs-title="Cycles through all sides!"
>
All breakpoints
</button>
</div>
</div>
<hr class="my-4">
<h2>Non-Responsive (Unchanged Behavior)</h2>
<p>These use the standard single-value placement and should work as before:</p>
<div class="d-flex gap-3 justify-content-center mt-4">
<div class="dropdown">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-placement="top" aria-expanded="false">
Top
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
</ul>
</div>
<div class="dropdown">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-placement="bottom" aria-expanded="false">
Bottom
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
</ul>
</div>
<div class="dropdown">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-placement="left" aria-expanded="false">
Left
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
</ul>
</div>
<div class="dropdown">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-placement="right" aria-expanded="false">
Right
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
</ul>
</div>
</div>
<hr class="my-4">
<h2>Breakpoint Reference</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Breakpoint</th>
<th>Min Width</th>
<th>Syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>xs</code></td>
<td>0</td>
<td><code>bottom</code> (default, no prefix)</td>
</tr>
<tr>
<td><code>sm</code></td>
<td>576px</td>
<td><code>sm:top</code></td>
</tr>
<tr>
<td><code>md</code></td>
<td>768px</td>
<td><code>md:right</code></td>
</tr>
<tr>
<td><code>lg</code></td>
<td>1024px</td>
<td><code>lg:left</code></td>
</tr>
<tr>
<td><code>xl</code></td>
<td>1280px</td>
<td><code>xl:bottom-end</code></td>
</tr>
<tr>
<td><code>2xl</code></td>
<td>1536px</td>
<td><code>2xl:top-start</code></td>
</tr>
</tbody>
</table>
</div>
<script src="../../../dist/js/bootstrap.bundle.js"></script>
<script>
// Initialize tooltips
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
new bootstrap.Tooltip(el)
})
// Update breakpoint indicator
function updateBreakpointIndicator() {
const width = window.innerWidth
let bp = 'xs'
if (width >= 1536) bp = '2xl'
else if (width >= 1280) bp = 'xl'
else if (width >= 1024) bp = 'lg'
else if (width >= 768) bp = 'md'
else if (width >= 576) bp = 'sm'
document.getElementById('breakpointIndicator').textContent = `${bp} (${width}px)`
}
window.addEventListener('resize', updateBreakpointIndicator)
updateBreakpointIndicator()
</script>
</body>
</html>

110
package-lock.json generated
View File

@ -28,11 +28,12 @@
"@babel/core": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"@docsearch/js": "^3.9.0",
"@popperjs/core": "^2.11.8",
"@oddbird/css-anchor-positioning": "^0.5.0",
"@rollup/plugin-babel": "^6.1.0",
"@rollup/plugin-commonjs": "^29.0.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-replace": "^6.0.3",
"@shikijs/transformers": "^3.15.0",
"@stackblitz/sdk": "^1.11.0",
"@types/js-yaml": "^4.0.9",
"@types/mime": "^4.0.0",
@ -40,6 +41,7 @@
"astro": "^5.15.6",
"astro-auto-import": "^0.4.5",
"autoprefixer": "^10.4.22",
"bootstrap-vscode-theme": "^0.0.9",
"bundlewatch": "^0.4.1",
"clean-css-cli": "^5.6.3",
"clipboard": "^2.0.11",
@ -93,7 +95,12 @@
"zod": "^4.1.12"
},
"peerDependencies": {
"@popperjs/core": "^2.11.8"
"@oddbird/css-anchor-positioning": "^0.5.0"
},
"peerDependenciesMeta": {
"@oddbird/css-anchor-positioning": {
"optional": true
}
}
},
"node_modules/@adobe/css-tools": {
@ -3000,6 +3007,34 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/@floating-ui/core": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",
"integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@floating-ui/utils": "^0.2.10"
}
},
"node_modules/@floating-ui/dom": {
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz",
"integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^1.7.3",
"@floating-ui/utils": "^0.2.10"
}
},
"node_modules/@floating-ui/utils": {
"version": "0.2.10",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz",
"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@html-validate/stylish": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@html-validate/stylish/-/stylish-4.3.0.tgz",
@ -3825,6 +3860,38 @@
"node": ">= 8"
}
},
"node_modules/@oddbird/css-anchor-positioning": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/@oddbird/css-anchor-positioning/-/css-anchor-positioning-0.5.2.tgz",
"integrity": "sha512-8QNyAY/zqAYbHyLf/cYaITjcFE7uCuudmgKGRdhEF2k8/2xz74P/gKB+MXJ7KtkGhI2cIPXDs0gc3T+0jOsjUg==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@floating-ui/dom": "^1.6.13",
"@types/css-tree": "^2.3.10",
"css-tree": "^3.1.0",
"nanoid": "^5.1.5"
}
},
"node_modules/@oddbird/css-anchor-positioning/node_modules/nanoid": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.6.tgz",
"integrity": "sha512-c7+7RQ+dMB5dPwwCp4ee1/iV/q2P6aK1mTZcfr1BTuVlyW9hJYiMPybJCcnBlQtuSmTIWNeazm/zqNoZSSElBg==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^18 || >=20"
}
},
"node_modules/@oslojs/encoding": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@oslojs/encoding/-/encoding-1.1.0.tgz",
@ -4166,17 +4233,6 @@
"node": ">=14"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"dev": true,
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@rollup/plugin-babel": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-6.1.0.tgz",
@ -4686,6 +4742,17 @@
"@shikijs/types": "3.15.0"
}
},
"node_modules/@shikijs/transformers": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-3.15.0.tgz",
"integrity": "sha512-Hmwip5ovvSkg+Kc41JTvSHHVfCYF+C8Cp1omb5AJj4Xvd+y9IXz2rKJwmFRGsuN0vpHxywcXJ1+Y4B9S7EG1/A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/core": "3.15.0",
"@shikijs/types": "3.15.0"
}
},
"node_modules/@shikijs/types": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.15.0.tgz",
@ -4851,6 +4918,13 @@
"@types/node": "*"
}
},
"node_modules/@types/css-tree": {
"version": "2.3.11",
"resolved": "https://registry.npmjs.org/@types/css-tree/-/css-tree-2.3.11.tgz",
"integrity": "sha512-aEokibJOI77uIlqoBOkVbaQGC9zII0A+JH1kcTNKW2CwyYWD8KM6qdo+4c77wD3wZOQfJuNWAr9M4hdk+YhDIg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/debug": {
"version": "4.1.12",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
@ -5949,6 +6023,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/bootstrap-vscode-theme": {
"version": "0.0.9",
"resolved": "https://registry.npmjs.org/bootstrap-vscode-theme/-/bootstrap-vscode-theme-0.0.9.tgz",
"integrity": "sha512-++aMildSGVaDS7qD59FEh4Fh6bJol4Gpo7u3rbEPqcuReRY7zOvLn77sBoK9zhVe+YT7bkPiDut47jErweChdw==",
"dev": true,
"license": "MIT",
"engines": {
"vscode": "^1.0.0"
}
},
"node_modules/boxen": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/boxen/-/boxen-8.0.1.tgz",

View File

@ -102,7 +102,12 @@
"astro-preview": "astro preview --root site --port 9001"
},
"peerDependencies": {
"@popperjs/core": "^2.11.8"
"@oddbird/css-anchor-positioning": "^0.5.0"
},
"peerDependenciesMeta": {
"@oddbird/css-anchor-positioning": {
"optional": true
}
},
"devDependencies": {
"@astrojs/check": "^0.9.5",
@ -114,11 +119,12 @@
"@babel/core": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"@docsearch/js": "^3.9.0",
"@popperjs/core": "^2.11.8",
"@oddbird/css-anchor-positioning": "^0.5.0",
"@rollup/plugin-babel": "^6.1.0",
"@rollup/plugin-commonjs": "^29.0.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-replace": "^6.0.3",
"@shikijs/transformers": "^3.15.0",
"@stackblitz/sdk": "^1.11.0",
"@types/js-yaml": "^4.0.9",
"@types/mime": "^4.0.0",
@ -126,6 +132,7 @@
"astro": "^5.15.6",
"astro-auto-import": "^0.4.5",
"autoprefixer": "^10.4.22",
"bootstrap-vscode-theme": "^0.0.9",
"bundlewatch": "^0.4.1",
"clean-css-cli": "^5.6.3",
"clipboard": "^2.0.11",
@ -193,14 +200,12 @@
},
"shim": {
"js/bootstrap": {
"deps": [
"@popperjs/core"
]
"deps": []
}
},
"dependencies": {},
"peerDependencies": {
"@popperjs/core": "^2.11.8"
"@oddbird/css-anchor-positioning": "^0.5.0"
}
},
"overrides": {

View File

@ -0,0 +1,253 @@
@use "config" as *;
// scss-docs-start anchor-positioning
// Native CSS Anchor Positioning support
// This file provides the foundational styles for anchor-positioned elements
// like tooltips, popovers, and dropdowns using the CSS Anchor Positioning API.
//
// Browser support: Chrome 125+, requires polyfill for Firefox/Safari
// Polyfill: @oddbird/css-anchor-positioning
// scss-docs-end anchor-positioning
// Base styles for anchor-positioned elements
@layer components {
// Elements that can be positioned using anchor positioning
// Only apply fixed positioning when CSS anchor positioning is supported
@supports (anchor-name: --test) {
.tooltip,
.popover,
.dropdown-menu {
// Use fixed positioning for anchor-positioned elements
// The anchor positioning properties will override inset values
position: fixed;
inset: auto;
margin: 0;
overflow: visible;
// Position try fallbacks for automatic repositioning
// when the element would overflow the viewport
position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
// Ensure proper stacking - hide when anchor scrolls out of view
position-visibility: anchors-visible;
}
}
// For dropdowns in sticky/fixed navbars, use absolute positioning instead
// of anchor positioning to avoid jitter during scroll. The dropdown wrapper
// (b-dropdown or .dropdown) provides the positioning context.
.sticky-top,
.sticky-bottom,
.fixed-top,
.fixed-bottom {
b-dropdown,
.dropdown,
.dropup,
.dropend,
.dropstart {
position: relative;
}
.dropdown-menu {
position: absolute;
// Reset anchor positioning (may be set via inline styles)
position-anchor: unset;
// Position below toggle by default (top, right, bottom, left order)
top: 100%;
right: auto;
bottom: auto;
left: 0;
}
// Handle dropup in sticky context
.dropup .dropdown-menu {
top: auto;
bottom: 100%;
}
// Handle dropend in sticky context
.dropend .dropdown-menu {
top: 0;
left: 100%;
}
// Handle dropstart in sticky context
.dropstart .dropdown-menu {
top: 0;
right: 100%;
left: auto;
}
}
// Popover API integration
// When using the native Popover API, elements are placed in the top layer
// This works independently of CSS anchor positioning
@supports selector(:popover-open) {
.tooltip[popover],
.popover[popover] {
// Popover open state
&:popover-open {
display: block;
}
// Entry animation
@starting-style {
&:popover-open {
opacity: 0;
transform: scale(.95);
}
}
}
.dropdown-menu[popover] {
// Dropdown menus use flex for gap spacing
&:popover-open {
display: flex;
}
// Entry animation
@starting-style {
&:popover-open {
opacity: 0;
transform: scale(.95);
}
}
}
}
// Offset custom properties applied via JavaScript
// Offset format: [skidding, distance] (same as Popper.js)
// - skidding: shifts along the edge (perpendicular to placement direction)
// - distance: pushes away from anchor (in the placement direction)
.tooltip,
.popover {
--bs-position-skidding: 0;
--bs-position-distance: 0;
// Vertical placements: skidding = horizontal, distance = vertical
&[data-bs-placement="top"],
&[data-bs-placement="top-start"],
&[data-bs-placement="top-end"] {
margin-block-end: var(--bs-position-distance);
margin-inline-start: var(--bs-position-skidding);
}
&[data-bs-placement="bottom"],
&[data-bs-placement="bottom-start"],
&[data-bs-placement="bottom-end"] {
margin-block-start: var(--bs-position-distance);
margin-inline-start: var(--bs-position-skidding);
}
// Horizontal placements: skidding = vertical, distance = horizontal
&[data-bs-placement="left"],
&[data-bs-placement="left-start"],
&[data-bs-placement="left-end"] {
margin-block-start: var(--bs-position-skidding);
margin-inline-end: var(--bs-position-distance);
}
&[data-bs-placement="right"],
&[data-bs-placement="right-start"],
&[data-bs-placement="right-end"] {
margin-block-start: var(--bs-position-skidding);
margin-inline-start: var(--bs-position-distance);
}
}
// Dropdown specific offsets
// Offset format: [skidding, distance] (same as Popper.js)
// - skidding: shifts along the edge (perpendicular to placement direction)
// - distance: pushes away from anchor (in the placement direction)
.dropdown-menu {
--bs-position-skidding: 0;
--bs-position-distance: 0;
// Vertical dropdowns (default and dropup)
// skidding = horizontal shift, distance = vertical push
&[data-bs-placement="bottom"],
&[data-bs-placement="bottom-start"],
&[data-bs-placement="bottom-end"] {
margin-block-start: calc(var(--#{$prefix}dropdown-spacer) + var(--bs-position-distance, 0));
margin-inline-start: var(--bs-position-skidding, 0);
}
&[data-bs-placement="top"],
&[data-bs-placement="top-start"],
&[data-bs-placement="top-end"] {
margin-block-end: calc(var(--#{$prefix}dropdown-spacer) + var(--bs-position-distance, 0));
margin-inline-start: var(--bs-position-skidding, 0);
}
// Horizontal dropdowns (dropstart and dropend)
// skidding = vertical shift, distance = horizontal push
&[data-bs-placement="right"],
&[data-bs-placement="right-start"],
&[data-bs-placement="right-end"] {
margin-block-start: var(--bs-position-skidding, 0);
margin-inline-start: calc(var(--#{$prefix}dropdown-spacer) + var(--bs-position-distance, 0));
}
&[data-bs-placement="left"],
&[data-bs-placement="left-start"],
&[data-bs-placement="left-end"] {
margin-block-start: var(--bs-position-skidding, 0);
margin-inline-end: calc(var(--#{$prefix}dropdown-spacer) + var(--bs-position-distance, 0));
}
}
// Arrow positioning using anchor positioning
// Arrows are positioned at the center of the anchor element
@supports (anchor-name: --test) {
.tooltip-arrow,
.popover-arrow {
position: absolute;
// Arrow positioning relative to the anchor
// Uses anchor() function to calculate position
[data-bs-placement="top"] > &,
[data-bs-placement="top-start"] > &,
[data-bs-placement="top-end"] > & {
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
[data-bs-placement="bottom"] > &,
[data-bs-placement="bottom-start"] > &,
[data-bs-placement="bottom-end"] > & {
top: 0;
left: 50%;
transform: translateX(-50%);
}
[data-bs-placement="left"] > &,
[data-bs-placement="left-start"] > &,
[data-bs-placement="left-end"] > & {
top: 50%;
right: 0;
transform: translateY(-50%);
}
[data-bs-placement="right"] > &,
[data-bs-placement="right-start"] > &,
[data-bs-placement="right-end"] > & {
// top: anchor(center);
top: 50%;
left: 0;
transform: translateY(-50%);
}
}
}
// Fallback arrow positioning when anchor positioning is not supported
@supports not (anchor-name: --test) {
.tooltip-arrow,
.popover-arrow {
position: absolute;
// Center the arrow using traditional CSS
// Specific positioning is handled in component SCSS files
}
}
}

View File

@ -11,15 +11,16 @@
@use "layout/breakpoints" as *;
// scss-docs-start dropdown-variables
$dropdown-gap: $spacer * .125 !default;
$dropdown-min-width: 10rem !default;
$dropdown-padding-x: 0 !default;
$dropdown-padding-y: .5rem !default;
$dropdown-padding-x: .25rem !default;
$dropdown-padding-y: .25rem !default;
$dropdown-spacer: .125rem !default;
$dropdown-font-size: $font-size-base !default;
$dropdown-color: var(--#{$prefix}color-body) !default;
$dropdown-bg: var(--#{$prefix}bg-body) !default;
$dropdown-border-color: var(--#{$prefix}border-color-translucent) !default;
$dropdown-border-radius: var(--#{$prefix}border-radius) !default;
$dropdown-border-radius: var(--#{$prefix}border-radius-lg) !default;
$dropdown-border-width: var(--#{$prefix}border-width) !default;
$dropdown-inner-border-radius: calc(#{$dropdown-border-radius} - #{$dropdown-border-width}) !default;
$dropdown-divider-bg: $dropdown-border-color !default;
@ -28,15 +29,17 @@ $dropdown-box-shadow: var(--#{$prefix}box-shadow) !default;
$dropdown-link-color: var(--#{$prefix}color-body) !default;
$dropdown-link-hover-color: $dropdown-link-color !default;
$dropdown-link-hover-bg: var(--#{$prefix}tertiary-bg) !default;
$dropdown-link-hover-bg: var(--#{$prefix}bg-1) !default;
$dropdown-link-active-color: $component-active-color !default;
$dropdown-link-active-bg: $component-active-bg !default;
$dropdown-link-disabled-color: var(--#{$prefix}tertiary-color) !default;
$dropdown-link-disabled-color: var(--#{$prefix}fg-3) !default;
$dropdown-item-padding-y: $spacer * .25 !default;
$dropdown-item-padding-x: $spacer !default;
$dropdown-item-border-radius: var(--#{$prefix}border-radius) !default;
$dropdown-item-gap: $spacer * .5 !default;
$dropdown-header-color: var(--#{$prefix}gray-600) !default;
$dropdown-header-padding-x: $dropdown-item-padding-x !default;
@ -45,7 +48,7 @@ $dropdown-header-padding-y: $dropdown-padding-y !default;
// scss-docs-start dropdown-dark-variables
$dropdown-dark-color: var(--#{$prefix}gray-300) !default;
$dropdown-dark-bg: var(--#{$prefix}gray-800) !default;
$dropdown-dark-bg: var(--#{$prefix}gray-900) !default;
$dropdown-dark-border-color: $dropdown-border-color !default;
$dropdown-dark-divider-bg: $dropdown-divider-bg !default;
$dropdown-dark-box-shadow: null !default;
@ -59,14 +62,15 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
// scss-docs-end dropdown-dark-variables
@layer components {
// The dropdown wrapper (`<div>`)
// The dropdown wrapper (custom element or class)
b-dropdown,
.dropup,
.dropend,
.dropdown,
.dropstart,
.dropup-center,
.dropdown-center {
position: relative;
// No positioning needed - anchor positioning handles this
}
.dropdown-toggle {
@ -80,6 +84,7 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
.dropdown-menu {
// scss-docs-start dropdown-css-vars
--#{$prefix}dropdown-zindex: #{$zindex-dropdown};
--#{$prefix}dropdown-gap: #{$dropdown-gap};
--#{$prefix}dropdown-min-width: #{$dropdown-min-width};
--#{$prefix}dropdown-padding-x: #{$dropdown-padding-x};
--#{$prefix}dropdown-padding-y: #{$dropdown-padding-y};
@ -100,8 +105,10 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
--#{$prefix}dropdown-link-active-color: #{$dropdown-link-active-color};
--#{$prefix}dropdown-link-active-bg: #{$dropdown-link-active-bg};
--#{$prefix}dropdown-link-disabled-color: #{$dropdown-link-disabled-color};
--#{$prefix}dropdown-item-gap: #{$dropdown-item-gap};
--#{$prefix}dropdown-item-padding-x: #{$dropdown-item-padding-x};
--#{$prefix}dropdown-item-padding-y: #{$dropdown-item-padding-y};
--#{$prefix}dropdown-item-border-radius: #{$dropdown-item-border-radius};
--#{$prefix}dropdown-header-color: #{$dropdown-header-color};
--#{$prefix}dropdown-header-padding-x: #{$dropdown-header-padding-x};
--#{$prefix}dropdown-header-padding-y: #{$dropdown-header-padding-y};
@ -110,6 +117,8 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
position: absolute;
z-index: var(--#{$prefix}dropdown-zindex);
display: none; // none by default, but block on "open" of the menu
flex-direction: column;
gap: var(--#{$prefix}dropdown-gap);
min-width: var(--#{$prefix}dropdown-min-width);
padding: var(--#{$prefix}dropdown-padding-y) var(--#{$prefix}dropdown-padding-x);
margin: 0; // Override default margin of ul
@ -123,10 +132,11 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
@include border-radius(var(--#{$prefix}dropdown-border-radius));
@include box-shadow(var(--#{$prefix}dropdown-box-shadow));
&[data-bs-popper] {
top: 100%;
// Native anchor positioning fallback
// Note: margin handled by _anchor-positioning.scss based on placement
&[data-bs-placement] {
top: 0;
left: 0;
margin-top: var(--#{$prefix}dropdown-spacer);
}
@if $dropdown-padding-y == 0 {
@ -138,95 +148,99 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
> li:last-child .dropdown-item {
@include border-bottom-radius(var(--#{$prefix}dropdown-inner-border-radius));
}
}
}
// scss-docs-start responsive-breakpoints
// We deliberately hardcode the `bs-` prefix because we check
// this custom property in JS to determine Popper's positioning
// // scss-docs-start responsive-breakpoints
// // We deliberately hardcode the `bs-` prefix because we check
// // this custom property in JS to determine Popper's positioning
@each $breakpoint in map.keys($grid-breakpoints) {
@include media-breakpoint-up($breakpoint) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
// @each $breakpoint in map.keys($grid-breakpoints) {
// @include media-breakpoint-up($breakpoint) {
// $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
.dropdown-menu#{$infix}-start {
--bs-position: start;
// .dropdown-menu#{$infix}-start {
// --bs-position: start;
&[data-bs-popper] {
right: auto;
left: 0;
}
}
// &[data-bs-placement],
// &[data-bs-popper] {
// right: auto;
// left: 0;
// }
// }
.dropdown-menu#{$infix}-end {
--bs-position: end;
// .dropdown-menu#{$infix}-end {
// --bs-position: end;
&[data-bs-popper] {
right: 0;
left: auto;
}
}
}
}
// scss-docs-end responsive-breakpoints
// &[data-bs-placement],
// &[data-bs-popper] {
// right: 0;
// left: auto;
// }
// }
// }
// }
// // scss-docs-end responsive-breakpoints
// Allow for dropdowns to go bottom up (aka, dropup-menu)
// Just add .dropup after the standard .dropdown class and you're set.
.dropup {
.dropdown-menu[data-bs-popper] {
top: auto;
bottom: 100%;
margin-top: 0;
margin-bottom: var(--#{$prefix}dropdown-spacer);
}
// // Allow for dropdowns to go bottom up (aka, dropup-menu)
// // Just add .dropup after the standard .dropdown class and you're set.
// .dropup {
// .dropdown-menu[data-bs-placement],
// .dropdown-menu[data-bs-popper] {
// top: auto;
// bottom: 100%;
// margin-top: 0;
// margin-bottom: var(--#{$prefix}dropdown-spacer);
// }
.dropdown-toggle {
@include caret(up);
}
}
// .dropdown-toggle {
// @include caret(up);
// }
// }
.dropend {
.dropdown-menu[data-bs-popper] {
top: 0;
right: auto;
left: 100%;
margin-inline-start: var(--#{$prefix}dropdown-spacer);
margin-top: 0;
}
// .dropend {
// .dropdown-menu[data-bs-placement],
// .dropdown-menu[data-bs-popper] {
// top: 0;
// right: auto;
// left: 100%;
// margin-inline-start: var(--#{$prefix}dropdown-spacer);
// margin-top: 0;
// }
.dropdown-toggle {
@include caret(end);
&::after {
vertical-align: 0;
}
}
}
// .dropdown-toggle {
// @include caret(end);
// &::after {
// vertical-align: 0;
// }
// }
// }
.dropstart {
.dropdown-menu[data-bs-popper] {
top: 0;
right: 100%;
left: auto;
margin-inline-end: var(--#{$prefix}dropdown-spacer);
margin-top: 0;
}
// .dropstart {
// .dropdown-menu[data-bs-placement],
// .dropdown-menu[data-bs-popper] {
// top: 0;
// right: 100%;
// left: auto;
// margin-inline-end: var(--#{$prefix}dropdown-spacer);
// margin-top: 0;
// }
.dropdown-toggle {
@include caret(start);
&::before {
vertical-align: 0;
}
}
}
// .dropdown-toggle {
// @include caret(start);
// &::before {
// vertical-align: 0;
// }
// }
// }
// Dividers (basically an `<hr>`) within the dropdown
.dropdown-divider {
height: 0;
margin: var(--#{$prefix}dropdown-divider-margin-y) 0;
margin: var(--#{$prefix}dropdown-divider-margin-y);
overflow: hidden;
border-block-start: 1px solid var(--#{$prefix}dropdown-divider-bg);
border-block-start: .5px solid var(--#{$prefix}dropdown-divider-bg);
opacity: 1; // Revisit in v6 to de-dupe styles that conflict with <hr> element
}
@ -234,10 +248,13 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
//
// `<button>`-specific styles are denoted with `// For <button>s`
.dropdown-item {
display: block;
display: flex;
gap: var(--#{$prefix}dropdown-item-gap);
align-items: center;
// justify-content: flex-start;
width: 100%; // For `<button>`s
padding: var(--#{$prefix}dropdown-item-padding-y) var(--#{$prefix}dropdown-item-padding-x);
clear: both;
// clear: both;
font-weight: $font-weight-normal;
color: var(--#{$prefix}dropdown-link-color);
text-align: inherit; // For `<button>`s
@ -269,25 +286,26 @@ $dropdown-dark-header-color: var(--#{$prefix}gray-500) !default;
}
}
.dropdown-menu.show {
display: block;
}
// Dropdown section headers
.dropdown-header {
display: block;
display: flex;
gap: var(--#{$prefix}dropdown-item-gap);
align-items: center;
padding: var(--#{$prefix}dropdown-header-padding-y) var(--#{$prefix}dropdown-header-padding-x);
margin-top: var(--#{$prefix}dropdown-header-padding-y);
margin-bottom: 0; // for use with heading elements
@include font-size($font-size-sm);
font-size: var(--#{$prefix}font-size-xs);
color: var(--#{$prefix}dropdown-header-color);
white-space: nowrap; // as with > li > a
}
// Dropdown text
.dropdown-item-text {
display: block;
display: flex;
gap: var(--#{$prefix}dropdown-item-gap);
align-items: center;
padding: var(--#{$prefix}dropdown-item-padding-y) var(--#{$prefix}dropdown-item-padding-x);
color: var(--#{$prefix}dropdown-link-color);
color: var(--#{$prefix}fg-2);
}
// Dark dropdowns

View File

@ -6,7 +6,7 @@
@use "mixins/reset-text" as *;
// scss-docs-start popover-variables
$popover-font-size: $font-size-sm !default;
$popover-font-size: var(--#{$prefix}font-size-sm) !default;
$popover-bg: var(--#{$prefix}bg-body) !default;
$popover-max-width: 276px !default;
$popover-border-width: var(--#{$prefix}border-width) !default;
@ -16,7 +16,7 @@ $popover-inner-border-radius: calc(#{$popover-border-radius} - #{$popover-
$popover-box-shadow: var(--#{$prefix}box-shadow) !default;
$popover-header-font-size: $font-size-base !default;
$popover-header-bg: var(--#{$prefix}secondary-bg) !default;
$popover-header-bg: var(--#{$prefix}bg-1) !default;
$popover-header-color: $headings-color !default;
$popover-header-padding-y: .5rem !default;
$popover-header-padding-x: $spacer !default;
@ -57,6 +57,7 @@ $popover-arrow-height: .5rem !default;
z-index: var(--#{$prefix}popover-zindex);
display: block;
max-width: var(--#{$prefix}popover-max-width);
padding: 0; // Reset default popover styles
// Our parent element can be arbitrary since tooltips are by default inserted as a sibling of their target element.
// So reset our font and text properties to avoid inheriting weird values.
@include reset-text();
@ -186,17 +187,19 @@ $popover-arrow-height: .5rem !default;
}
}
// Auto placement - responds to data-bs-placement attribute (native anchor positioning)
.bs-popover-auto {
&[data-popper-placement^="top"] {
// Native anchor positioning using data-bs-placement
&[data-bs-placement^="top"] {
@extend .bs-popover-top;
}
&[data-popper-placement^="right"] {
&[data-bs-placement^="right"] {
@extend .bs-popover-end;
}
&[data-popper-placement^="bottom"] {
&[data-bs-placement^="bottom"] {
@extend .bs-popover-bottom;
}
&[data-popper-placement^="left"] {
&[data-bs-placement^="left"] {
@extend .bs-popover-start;
}
}

View File

@ -9,7 +9,7 @@
$tooltip-font-size: $font-size-sm !default;
$tooltip-max-width: 200px !default;
$tooltip-color: var(--#{$prefix}bg-body) !default;
$tooltip-bg: var(--#{$prefix}color-body) !default;
$tooltip-bg: var(--#{$prefix}fg-body) !default;
$tooltip-border-radius: var(--#{$prefix}border-radius) !default;
$tooltip-opacity: .9 !default;
$tooltip-padding-y: $spacer * .25 !default;
@ -58,6 +58,7 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
@include font-size(var(--#{$prefix}tooltip-font-size));
// Allow breaking very long words so they don't overflow the tooltip's bounds
word-wrap: break-word;
border: 0;
opacity: 0;
&.show { opacity: var(--#{$prefix}tooltip-opacity); }
@ -76,6 +77,7 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
}
}
// Top placement
.bs-tooltip-top .tooltip-arrow {
bottom: calc(-1 * var(--#{$prefix}tooltip-arrow-height));
@ -86,6 +88,7 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
}
}
// End/Right placement
.bs-tooltip-end .tooltip-arrow {
left: calc(-1 * var(--#{$prefix}tooltip-arrow-height));
width: var(--#{$prefix}tooltip-arrow-height);
@ -98,6 +101,7 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
}
}
// Bottom placement
.bs-tooltip-bottom .tooltip-arrow {
top: calc(-1 * var(--#{$prefix}tooltip-arrow-height));
@ -108,6 +112,7 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
}
}
// Start/Left placement
.bs-tooltip-start .tooltip-arrow {
right: calc(-1 * var(--#{$prefix}tooltip-arrow-height));
width: var(--#{$prefix}tooltip-arrow-height);
@ -120,7 +125,23 @@ $form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
}
}
// Auto placement - responds to data-bs-placement attribute (native anchor positioning)
.bs-tooltip-auto {
// Native anchor positioning using data-bs-placement
&[data-bs-placement^="top"] {
@extend .bs-tooltip-top;
}
&[data-bs-placement^="right"] {
@extend .bs-tooltip-end;
}
&[data-bs-placement^="bottom"] {
@extend .bs-tooltip-bottom;
}
&[data-bs-placement^="left"] {
@extend .bs-tooltip-start;
}
// Legacy Popper support (deprecated)
&[data-popper-placement^="top"] {
@extend .bs-tooltip-top;
}

3
scss/bootstrap.scss vendored
View File

@ -4,6 +4,9 @@
// Global CSS variables, layer definitions, and configuration
@forward "root";
// Native CSS anchor positioning support
@forward "anchor-positioning";
// Subdir imports
@forward "content";
@forward "layout";

View File

@ -1 +1 @@
Feel free to use either `title` or `data-bs-title` in your HTML. When `title` is used, Popper will replace it automatically with `data-bs-title` when the element is rendered.
Use `title` or `data-bs-title` in your HTML. When `title` is used, Bootstrap will replace it automatically with `data-bs-title` when the element is rendered.

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,35 @@
---
title: Popovers
description: Documentation and examples for adding Bootstrap popovers, like those found in iOS, to any element on your site.
description: Popovers are built on top of the HTML Popover API and Anchor Positioning API through polyfills. Use them to display content in a popover when a user clicks on a button or other element.
mdn: https://developer.mozilla.org/en-US/docs/Web/API/Popover_API
toc: true
---
## Overview
## Example
Popovers can be triggered by clicking on an element with the appropriate data attributes:
- Enable popover functionality via `data-bs-toggle="popover"`.
- Set the body content with `data-bs-content`. Note content here will be sanitized.
- Set the optional title with `data-bs-title` or `title`. If `title` is used, Bootstrap will replace it automatically with `data-bs-title` when the element is rendered.
<Example addStackblitzJs code={`<button type="button"
class="btn btn-solid theme-primary"
data-bs-toggle="popover"
data-bs-title="Popover title"
data-bs-content="And here's some amazing content. It's very engaging. Right?">
Click to toggle popover
</button>`} />
## How they work
Things to know when using the popover plugin:
- Popovers rely on the third party library [Popper](https://popper.js.org/docs/v2/) for positioning. You must include [popper.min.js]([[config:cdn.popper]]) before `bootstrap.js`, or use one `bootstrap.bundle.min.js` which contains Popper.
- Popovers require the [popover plugin]([[docsref:/components/popovers]]) as a dependency.
- Popovers are opt-in for performance reasons, so **you must initialize them yourself**.
- Popovers use native CSS anchor positioning for placement (with automatic fallback for older browsers).
- Zero-length `title` and `content` values will never show a popover.
- Specify `container: 'body'` to avoid rendering problems in more complex components (like our input groups, button groups, etc).
- Triggering popovers on hidden elements will not work.
- Popovers for `.disabled` or `disabled` elements must be triggered on a wrapper element.
- When triggered from anchors that wrap across multiple lines, popovers will be centered between the anchors overall width. Use `.text-nowrap` on your `<a>`s to avoid this behavior.
- When triggered from anchors that wrap across multiple lines, popovers will be centered between the anchors' overall width. Use `.text-nowrap` on your `<a>`s to avoid this behavior.
- Popovers must be hidden before their corresponding elements have been removed from the DOM.
- Popovers can be triggered thanks to an element inside a shadow DOM.
@ -25,67 +39,30 @@ Things to know when using the popover plugin:
Keep reading to see how popovers work with some examples.
## Examples
### Enable popovers
As mentioned above, you must initialize popovers before they can be used. One way to initialize all popovers on a page would be to select them by their `data-bs-toggle` attribute, like so:
```js
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))
```
### Live demo
We use JavaScript similar to the snippet above to render the following live popover. Titles are set via `data-bs-title` and body content is set via `data-bs-content`.
<Callout name="warning-data-bs-title-vs-title" type="warning" />
<Example addStackblitzJs code={`<button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" data-bs-title="Popover title" data-bs-content="And heres some amazing content. Its very engaging. Right?">Click to toggle popover</button>`} />
### Four directions
## Directions
Four options are available: top, right, bottom, and left. Directions are mirrored when using Bootstrap in RTL. Set `data-bs-placement` to change the direction.
<Example addStackblitzJs code={`<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="top" data-bs-content="Top popover">
<Example addStackblitzJs code={`<button type="button" class="btn btn-solid theme-secondary" data-bs-toggle="popover" data-bs-placement="top" data-bs-content="Top popover">
Popover on top
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="right" data-bs-content="Right popover">
<button type="button" class="btn btn-solid theme-secondary" data-bs-toggle="popover" data-bs-placement="right" data-bs-content="Right popover">
Popover on right
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content="Bottom popover">
<button type="button" class="btn btn-solid theme-secondary" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content="Bottom popover">
Popover on bottom
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="left" data-bs-content="Left popover">
<button type="button" class="btn btn-solid theme-secondary" data-bs-toggle="popover" data-bs-placement="left" data-bs-content="Left popover">
Popover on left
</button>`} />
### Custom `container`
When you have some styles on a parent element that interfere with a popover, youll want to specify a custom `container` so that the popovers HTML appears within that element instead. This is common in responsive tables, input groups, and the like.
```js
const popover = new bootstrap.Popover('.example-popover', {
container: 'body'
})
```
Another situation where youll want to set an explicit custom `container` are popovers inside a [modal dialog]([[docsref:/components/modal]]), to make sure that the popover itself is appended to the modal. This is particularly important for popovers that contain interactive elements modal dialogs will trap focus, so unless the popover is a child element of the modal, users wont be able to focus or activate these interactive elements.
```js
const popover = new bootstrap.Popover('.example-popover', {
container: '.modal-body'
})
```
### Custom popovers
## Custom styles
You can customize the appearance of popovers using [CSS variables](#variables). We set a custom class with `data-bs-custom-class="custom-popover"` to scope our custom appearance and use it to override some of the local CSS variables.
<ScssDocs name="custom-popovers" file="site/src/scss/_component-examples.scss" />
<Example addStackblitzJs class="custom-popover-demo" code={`<button type="button" class="btn btn-secondary"
<Example addStackblitzJs class="custom-popover-demo" code={`<button type="button" class="btn btn-solid theme-secondary"
data-bs-toggle="popover" data-bs-placement="right"
data-bs-custom-class="custom-popover"
data-bs-title="Custom popover"
@ -93,25 +70,21 @@ You can customize the appearance of popovers using [CSS variables](#variables).
Custom popover
</button>`} />
## Options
### Dismiss on next click
Use the `focus` trigger to dismiss popovers on the users next click of an element other than the toggle element.
Use the `focus` trigger to dismiss popovers on the user's next click of an element other than the toggle element.
<Callout type="danger">
**Dismissing on next click requires specific HTML for proper cross-browser and cross-platform behavior.** You can only use `<a>` elements, not `<button>`s, and you must include a [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex).
</Callout>
<Example addStackblitzJs code={`<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-bs-toggle="popover" data-bs-trigger="focus" data-bs-title="Dismissible popover" data-bs-content="And heres some amazing content. Its very engaging. Right?">Dismissible popover</a>`} />
```js
const popover = new bootstrap.Popover('.popover-dismiss', {
trigger: 'focus'
})
```
<Example addStackblitzJs code={`<a tabindex="0" class="btn btn-solid theme-primary" role="button" data-bs-toggle="popover" data-bs-trigger="focus" data-bs-title="Dismissible popover" data-bs-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover</a>`} />
### Disabled elements
Elements with the `disabled` attribute arent interactive, meaning users cannot hover or click them to trigger a popover (or tooltip). As a workaround, youll want to trigger the popover from a wrapper `<div>` or `<span>`, ideally made keyboard-focusable using `tabindex="0"`.
Elements with the `disabled` attribute aren't interactive, meaning users cannot hover or click them to trigger a popover (or tooltip). As a workaround, you'll want to trigger the popover from a wrapper `<div>` or `<span>`, ideally made keyboard-focusable using `tabindex="0"`.
For disabled popover triggers, you may also prefer `data-bs-trigger="hover focus"` so that the popover appears as immediate visual feedback to your users as they may not expect to _click_ on a disabled element.
@ -133,7 +106,7 @@ For disabled popover triggers, you may also prefer `data-bs-trigger="hover focus
## Usage
Enable popovers via JavaScript:
Popovers are automatically initialized when using `data-bs-toggle="popover"`. You can also create them programmatically via JavaScript:
```js
const exampleEl = document.getElementById('example')
@ -143,7 +116,7 @@ const popover = new bootstrap.Popover(exampleEl, options)
<Callout type="warning">
**Keep popovers accessible to keyboard and assistive technology users** by only adding them to HTML elements that are traditionally keyboard-focusable and interactive (such as links or form controls). While other HTML elements can be made focusable by adding `tabindex="0"`, this can create annoying and confusing tab stops on non-interactive elements for keyboard users, and most assistive technologies currently do not announce popovers in this situation. Additionally, do not rely solely on `hover` as the trigger for your popovers as this will make them impossible to trigger for keyboard users.
Avoid adding an excessive amount of content in popovers with the `html` option. Once popovers are displayed, their content is tied to the trigger element with the `aria-describedby` attribute, causing all of the popovers content to be announced to assistive technology users as one long, uninterrupted stream.
Avoid adding an excessive amount of content in popovers with the `html` option. Once popovers are displayed, their content is tied to the trigger element with the `aria-describedby` attribute, causing all of the popover's content to be announced to assistive technology users as one long, uninterrupted stream.
Popovers do not manage keyboard focus order, and their placement can be random in the DOM, so be careful when adding interactive elements (like forms or links), as it may lead to an illogical focus order or make the popover content itself completely unreachable for keyboard users. In cases where you must use these elements, consider using a modal dialog instead.
</Callout>
@ -159,22 +132,19 @@ Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` opt
<BsTable>
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowList` | object | [Default value]([[docsref:/getting-started/javascript#sanitizer]]) | An object containing allowed tags and attributes. Those not explicitly allowed will be removed by [the content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]). <Callout type="warning">**Exercise caution when adding to this list.** Refer to [OWASPs Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information.</Callout> |
| `allowList` | object | [Default value]([[docsref:/getting-started/javascript#sanitizer]]) | An object containing allowed tags and attributes. Those not explicitly allowed will be removed by [the content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]). <Callout type="warning">**Exercise caution when adding to this list.** Refer to [OWASP's Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information.</Callout> |
| `animation` | boolean | `true` | Apply a CSS fade transition to the popover. |
| `boundary` | string, element | `'clippingParents'` | Overflow constraint boundary of the popover (applies only to Poppers preventOverflow modifier). By default, its `'clippingParents'` and can accept an HTMLElement reference (via JavaScript only). For more information refer to Poppers [detectOverflow docs](https://popper.js.org/docs/v2/utils/detect-overflow/#boundary). |
| `container` | string, element, false | `false` | Appends the popover to a specific element. Example: `container: 'body'`. This option is particularly useful in that it allows you to position the popover in the flow of the document near the triggering element -&nbsp;which will prevent the popover from floating away from the triggering element during a window resize. |
| `content` | string, element, function | `''` | The popovers text content. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to. |
| `content` | string, element, function | `''` | The popover's text content. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to. |
| `customClass` | string, function | `''` | Add classes to the popover when it is shown. Note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces: `'class-1 class-2'`. You can also pass a function that should return a single string containing additional class names. |
| `delay` | number, object | `0` | Delay showing and hiding the popover (ms)—doesnt apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: `delay: { "show": 500, "hide": 100 }`. |
| `fallbackPlacements` | string, array | `['top', 'right', 'bottom', 'left']` | Define fallback placements by providing a list of placements in array (in order of preference). For more information refer to Poppers [behavior docs](https://popper.js.org/docs/v2/modifiers/flip/#fallbackplacements). |
| `html` | boolean | `false` | Allow HTML in the popover. If true, HTML tags in the popovers `title` will be rendered in the popover. If false, `innerText` property will be used to insert content into the DOM. Prefer text when dealing with user-generated input to [prevent XSS attacks](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html). |
| `offset` | number, string, function | `[0, 8]` | Offset of the popover relative to its target. You can pass a string in data attributes with comma separated values like: `data-bs-offset="10,20"`. When a function is used to determine the offset, it is called with an object containing the popper placement, the reference, and popper rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: [skidding](https://popper.js.org/docs/v2/modifiers/offset/#skidding-1), [distance](https://popper.js.org/docs/v2/modifiers/offset/#distance-1). For more information refer to Poppers [offset docs](https://popper.js.org/docs/v2/modifiers/offset/#options). |
| `delay` | number, object | `0` | Delay showing and hiding the popover (ms)—doesn't apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: `delay: { "show": 500, "hide": 100 }`. |
| `fallbackPlacements` | string, array | `['top', 'right', 'bottom', 'left']` | Define fallback placements by providing a list of placements in array (in order of preference). |
| `html` | boolean | `false` | Allow HTML in the popover. If true, HTML tags in the popover's `title` will be rendered in the popover. If false, `innerText` property will be used to insert content into the DOM. Prefer text when dealing with user-generated input to [prevent XSS attacks](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html). |
| `offset` | number, string, function | `[0, 8]` | Offset of the popover relative to its target. You can pass a string in data attributes with comma separated values like: `data-bs-offset="10,20"`. When a function is used to determine the offset, it is called with an object containing the placement, the reference, and positioned element rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: [skidding, distance]. |
| `placement` | string, function | `'right'` | How to position the popover: auto, top, bottom, left, right. When `auto` is specified, it will dynamically reorient the popover. When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The `this` context is set to the popover instance. |
| `popperConfig` | null, object, function | `null` | To change Bootstraps default Popper config, see [Poppers configuration](https://popper.js.org/docs/v2/constructors/#options). When a function is used to create the Popper configuration, its called with an object that contains the Bootstraps default Popper configuration. It helps you use and merge the default with your own configuration. The function must return a configuration object for Popper. |
| `sanitize` | boolean | `true` | Enable [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]). If true, the `template`, `content` and `title` options will be sanitized. <Callout type="warning">**Exercise caution when disabling content sanitization.** Refer to [OWASPs Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information. Vulnerabilities caused solely by disabling content sanitization are not considered within scope for Bootstraps security model.</Callout> |
| `sanitize` | boolean | `true` | Enable [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]). If true, the `template`, `content` and `title` options will be sanitized. <Callout type="warning">**Exercise caution when disabling content sanitization.** Refer to [OWASP's Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information. Vulnerabilities caused solely by disabling content sanitization are not considered within scope for Bootstrap's security model.</Callout> |
| `sanitizeFn` | null, function | `null` | Provide an alternative [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]) function. This can be useful if you prefer to use a dedicated library to perform sanitization. |
| `selector` | string, false | `false` | If a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to also apply popovers to dynamically added DOM elements (`jQuery.on` support). See [this issue]([[config:repo]]/issues/4215) and [an informative example](https://codepen.io/Johann-S/pen/djJYPb). **Note**: `title` attribute must not be used as a selector. |
| `template` | string | `'<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'` | Base HTML to use when creating the popover. The popovers `title` will be injected into the `.popover-header`. The popovers `content` will be injected into the `.popover-body`. `.popover-arrow` will become the popovers arrow. The outermost wrapper element should have the `.popover` class and `role="tooltip"`. |
| `template` | string | `'<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'` | Base HTML to use when creating the popover. The popover's `title` will be injected into the `.popover-header`. The popover's `content` will be injected into the `.popover-body`. `.popover-arrow` will become the popover's arrow. The outermost wrapper element should have the `.popover` class and `role="tooltip"`. |
| `title` | string, element, function | `''` | The popover title. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to. |
| `trigger` | string | `'click'` | How popover is triggered: click, hover, focus, manual. You may pass multiple triggers; separate them with a space. `'manual'` indicates that the popover will be triggered programmatically via the `.popover('show')`, `.popover('hide')` and `.popover('toggle')` methods; this value cannot be combined with any other trigger. `'hover'` on its own will result in popovers that cannot be triggered via the keyboard, and should only be used if alternative methods for conveying the same information for keyboard users is present. |
</BsTable>
@ -185,18 +155,6 @@ Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` opt
Options for individual popovers can alternatively be specified through the use of data attributes, as explained above.
</Callout>
#### Using function with `popperConfig`
```js
const popover = new bootstrap.Popover(element, {
popperConfig(defaultBsPopperConfig) {
// const newPopperConfig = {...}
// use defaultBsPopperConfig if needed...
// return newPopperConfig
}
})
```
### Methods
<Callout name="danger-async-methods" type="danger" />
@ -204,17 +162,17 @@ const popover = new bootstrap.Popover(element, {
<BsTable>
| Method | Description |
| --- | --- |
| `disable` | Removes the ability for an elements popover to be shown. The popover will only be able to be shown if it is re-enabled. |
| `dispose` | Hides and destroys an elements popover (Removes stored data on the DOM element). Popovers that use delegation (which are created using [the `selector` option](#options)) cannot be individually destroyed on descendant trigger elements. |
| `enable` | Gives an elements popover the ability to be shown. **Popovers are enabled by default.** |
| `disable` | Removes the ability for an element's popover to be shown. The popover will only be able to be shown if it is re-enabled. |
| `dispose` | Hides and destroys an element's popover (Removes stored data on the DOM element). Popovers that use delegation (which are created using [the `selector` option](#options)) cannot be individually destroyed on descendant trigger elements. |
| `enable` | Gives an element's popover the ability to be shown. **Popovers are enabled by default.** |
| `getInstance` | _Static_ method which allows you to get the popover instance associated with a DOM element. |
| `getOrCreateInstance` | _Static_ method which allows you to get the popover instance associated with a DOM element, or create a new one in case it wasnt initialized. |
| `hide` | Hides an elements popover. **Returns to the caller before the popover has actually been hidden** (i.e. before the `hidden.bs.popover` event occurs). This is considered a “manual” triggering of the popover. |
| `setContent` | Gives a way to change the popovers content after its initialization. |
| `show` | Reveals an elements popover. **Returns to the caller before the popover has actually been shown** (i.e. before the `shown.bs.popover` event occurs). This is considered a “manual” triggering of the popover. Popovers whose title and content are both zero-length are never displayed. |
| `toggle` | Toggles an elements popover. **Returns to the caller before the popover has actually been shown or hidden** (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). This is considered a “manual” triggering of the popover. |
| `toggleEnabled` | Toggles the ability for an elements popover to be shown or hidden. |
| `update` | Updates the position of an elements popover. |
| `getOrCreateInstance` | _Static_ method which allows you to get the popover instance associated with a DOM element, or create a new one in case it wasn't initialized. |
| `hide` | Hides an element's popover. **Returns to the caller before the popover has actually been hidden** (i.e. before the `hidden.bs.popover` event occurs). This is considered a "manual" triggering of the popover. |
| `setContent` | Gives a way to change the popover's content after its initialization. |
| `show` | Reveals an element's popover. **Returns to the caller before the popover has actually been shown** (i.e. before the `shown.bs.popover` event occurs). This is considered a "manual" triggering of the popover. Popovers whose title and content are both zero-length are never displayed. |
| `toggle` | Toggles an element's popover. **Returns to the caller before the popover has actually been shown or hidden** (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). This is considered a "manual" triggering of the popover. |
| `toggleEnabled` | Toggles the ability for an element's popover to be shown or hidden. |
| `update` | Updates the position of an element's popover. |
</BsTable>
```js

View File

@ -8,17 +8,15 @@ toc: true
Things to know when using the tooltip plugin:
- Tooltips rely on the third party library [Popper](https://popper.js.org/docs/v2/) for positioning. You must include [popper.min.js]([[config:cdn.popper]]) before `bootstrap.js`, or use one `bootstrap.bundle.min.js` which contains Popper.
- Tooltips are opt-in for performance reasons, so **you must initialize them yourself**.
- Tooltips use native CSS anchor positioning for placement (with automatic fallback for older browsers).
- Tooltips with zero-length titles are never displayed.
- Specify `container: 'body'` to avoid rendering problems in more complex components (like our input groups, button groups, etc).
- Triggering tooltips on hidden elements will not work.
- Tooltips for `.disabled` or `disabled` elements must be triggered on a wrapper element.
- When triggered from hyperlinks that span multiple lines, tooltips will be centered. Use `white-space: nowrap;` on your `<a>`s to avoid this behavior.
- Tooltips must be hidden before their corresponding elements have been removed from the DOM.
- Tooltips can be triggered thanks to an element inside a shadow DOM.
Got all that? Great, lets see how they work with some examples.
Got all that? Great, let's see how they work with some examples.
<Callout name="info-sanitizer" />
@ -26,20 +24,11 @@ Got all that? Great, lets see how they work with some examples.
## Examples
### Enable tooltips
As mentioned above, you must initialize tooltips before they can be used. One way to initialize all tooltips on a page would be to select them by their `data-bs-toggle` attribute, like so:
```js
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
```
### Tooltips on links
Hover over the links below to see tooltips:
<Example addStackblitzJs class="tooltip-demo" code={`<p class="muted">Placeholder text to demonstrate some <a href="#" data-bs-toggle="tooltip" data-bs-title="Default tooltip">inline links</a> with tooltips. This is now just filler, no killer. Content placed here just to mimic the presence of <a href="#" data-bs-toggle="tooltip" data-bs-title="Another tooltip">real text</a>. And all that just to give you an idea of how tooltips would look when used in real-world situations. So hopefully youve now seen how <a href="#" data-bs-toggle="tooltip" data-bs-title="Another one here too">these tooltips on links</a> can work in practice, once you use them on <a href="#" data-bs-toggle="tooltip" data-bs-title="The last tip!">your own</a> site or project.</p>`} />
<Example addStackblitzJs class="tooltip-demo" code={`<p class="muted">Placeholder text to demonstrate some <a href="#" data-bs-toggle="tooltip" data-bs-title="Default tooltip">inline links</a> with tooltips. This is now just filler, no killer. Content placed here just to mimic the presence of <a href="#" data-bs-toggle="tooltip" data-bs-title="Another tooltip">real text</a>. And all that just to give you an idea of how tooltips would look when used in real-world situations. So hopefully you've now seen how <a href="#" data-bs-toggle="tooltip" data-bs-title="Another one here too">these tooltips on links</a> can work in practice, once you use them on <a href="#" data-bs-toggle="tooltip" data-bs-title="The last tip!">your own</a> site or project.</p>`} />
<Callout name="warning-data-bs-title-vs-title" type="warning" />
@ -116,24 +105,15 @@ With an SVG:
## Usage
The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element. Trigger the tooltip via JavaScript:
The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element.
Tooltips are automatically initialized when using `data-bs-toggle="tooltip"`. You can also create them programmatically via JavaScript:
```js
const exampleEl = document.getElementById('example')
const tooltip = new bootstrap.Tooltip(exampleEl, options)
```
<Callout type="warning">
Tooltips automatically attempt to change positions when a parent container has `overflow: auto` or `overflow: scroll`, but still keeps the original placements positioning. Set the [`boundary` option](https://popper.js.org/docs/v2/modifiers/flip/#boundary) (for the flip modifier using the `popperConfig` option) to any HTMLElement to override the default value, `'clippingParents'`, such as `document.body`:
```js
const tooltip = new bootstrap.Tooltip('#example', {
boundary: document.body // or document.querySelector('#boundary')
})
```
</Callout>
### Markup
The required markup for a tooltip is only a `data` attribute and `title` on the HTML element you wish to have a tooltip. The generated markup of a tooltip is rather simple, though it does require a position (by default, set to `top` by the plugin).
@ -157,7 +137,7 @@ The required markup for a tooltip is only a `data` attribute and `title` on the
### Disabled elements
Elements with the `disabled` attribute arent interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). As a workaround, youll want to trigger the tooltip from a wrapper `<div>` or `<span>`, ideally made keyboard-focusable using `tabindex="0"`.
Elements with the `disabled` attribute aren't interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). As a workaround, you'll want to trigger the tooltip from a wrapper `<div>` or `<span>`, ideally made keyboard-focusable using `tabindex="0"`.
<Example class="tooltip-demo" addStackblitzJs code={`<span class="d-inline-block" tabindex="0" data-bs-toggle="tooltip" data-bs-title="Disabled tooltip">
<button class="btn btn-primary" type="button" disabled>Disabled button</button>
@ -174,21 +154,18 @@ Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` opt
<BsTable>
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowList` | object | [Default value]([[docsref:/getting-started/javascript#sanitizer]]) | An object containing allowed tags and attributes. Those not explicitly allowed will be removed by [the content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]). <Callout type="warning">**Exercise caution when adding to this list.** Refer to [OWASPs Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information.</Callout> |
| `allowList` | object | [Default value]([[docsref:/getting-started/javascript#sanitizer]]) | An object containing allowed tags and attributes. Those not explicitly allowed will be removed by [the content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]). <Callout type="warning">**Exercise caution when adding to this list.** Refer to [OWASP's Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information.</Callout> |
| `animation` | boolean | `true` | Apply a CSS fade transition to the tooltip. |
| `boundary` | string, element | `'clippingParents'` | Overflow constraint boundary of the tooltip (applies only to Poppers preventOverflow modifier). By default, its `'clippingParents'` and can accept an HTMLElement reference (via JavaScript only). For more information refer to Poppers [detectOverflow docs](https://popper.js.org/docs/v2/utils/detect-overflow/#boundary). |
| `container` | string, element, false | `false` | Appends the tooltip to a specific element. Example: `container: 'body'`. This option is particularly useful in that it allows you to position the tooltip in the flow of the document near the triggering element -&nbsp;which will prevent the tooltip from floating away from the triggering element during a window resize. |
| `customClass` | string, function | `''` | Add classes to the tooltip when it is shown. Note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces: `'class-1 class-2'`. You can also pass a function that should return a single string containing additional class names. |
| `delay` | number, object | `0` | Delay showing and hiding the tooltip (ms)—doesnt apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: `delay: { "show": 500, "hide": 100 }`. |
| `fallbackPlacements` | array | `['top', 'right', 'bottom', 'left']` | Define fallback placements by providing a list of placements in array (in order of preference). For more information refer to Poppers [behavior docs](https://popper.js.org/docs/v2/modifiers/flip/#fallbackplacements). |
| `html` | boolean | `false` | Allow HTML in the tooltip. If true, HTML tags in the tooltips `title` will be rendered in the tooltip. If false, `innerText` property will be used to insert content into the DOM. Prefer text when dealing with user-generated input to [prevent XSS attacks](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html). |
| `offset` | array, string, function | `[0, 6]` | Offset of the tooltip relative to its target. You can pass a string in data attributes with comma separated values like: `data-bs-offset="10,20"`. When a function is used to determine the offset, it is called with an object containing the popper placement, the reference, and popper rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: [skidding](https://popper.js.org/docs/v2/modifiers/offset/#skidding-1), [distance](https://popper.js.org/docs/v2/modifiers/offset/#distance-1). For more information refer to Poppers [offset docs](https://popper.js.org/docs/v2/modifiers/offset/#options). |
| `delay` | number, object | `0` | Delay showing and hiding the tooltip (ms)—doesn't apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: `delay: { "show": 500, "hide": 100 }`. |
| `fallbackPlacements` | array | `['top', 'right', 'bottom', 'left']` | Define fallback placements by providing a list of placements in array (in order of preference). |
| `html` | boolean | `false` | Allow HTML in the tooltip. If true, HTML tags in the tooltip's `title` will be rendered in the tooltip. If false, `innerText` property will be used to insert content into the DOM. Prefer text when dealing with user-generated input to [prevent XSS attacks](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html). |
| `offset` | array, string, function | `[0, 6]` | Offset of the tooltip relative to its target. You can pass a string in data attributes with comma separated values like: `data-bs-offset="10,20"`. When a function is used to determine the offset, it is called with an object containing the placement, the reference, and positioned element rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: [skidding, distance]. |
| `placement` | string, function | `'top'` | How to position the tooltip: auto, top, bottom, left, right. When `auto` is specified, it will dynamically reorient the tooltip. When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The `this` context is set to the tooltip instance. |
| `popperConfig` | null, object, function | `null` | To change Bootstraps default Popper config, see [Poppers configuration](https://popper.js.org/docs/v2/constructors/#options). When a function is used to create the Popper configuration, its called with an object that contains the Bootstraps default Popper configuration. It helps you use and merge the default with your own configuration. The function must return a configuration object for Popper. |
| `sanitize` | boolean | `true` | Enable [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]). If true, the `template`, `content` and `title` options will be sanitized. <Callout type="warning">**Exercise caution when disabling content sanitization.** Refer to [OWASPs Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information. Vulnerabilities caused solely by disabling content sanitization are not considered within scope for Bootstraps security model.</Callout> |
| `sanitize` | boolean | `true` | Enable [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]). If true, the `template`, `content` and `title` options will be sanitized. <Callout type="warning">**Exercise caution when disabling content sanitization.** Refer to [OWASP's Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) for more information. Vulnerabilities caused solely by disabling content sanitization are not considered within scope for Bootstrap's security model.</Callout> |
| `sanitizeFn` | null, function | `null` | Provide an alternative [content sanitization]([[docsref:/getting-started/javascript#sanitizer]]) function. This can be useful if you prefer to use a dedicated library to perform sanitization. |
| `selector` | string, false | `false` | If a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to also apply tooltips to dynamically added DOM elements (`jQuery.on` support). See [this issue]([[config:repo]]/issues/4215) and [an informative example](https://codepen.io/Johann-S/pen/djJYPb). **Note**: `title` attribute must not be used as a selector. |
| `template` | string | `'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'` | Base HTML to use when creating the tooltip. The tooltips `title` will be injected into the `.tooltip-inner`. `.tooltip-arrow` will become the tooltips arrow. The outermost wrapper element should have the `.tooltip` class and `role="tooltip"`. |
| `template` | string | `'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'` | Base HTML to use when creating the tooltip. The tooltip's `title` will be injected into the `.tooltip-inner`. `.tooltip-arrow` will become the tooltip's arrow. The outermost wrapper element should have the `.tooltip` class and `role="tooltip"`. |
| `title` | string, element, function | `''` | The tooltip title. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to. |
| `trigger` | string | `'hover focus'` | How tooltip is triggered: click, hover, focus, manual. You may pass multiple triggers; separate them with a space. `'manual'` indicates that the tooltip will be triggered programmatically via the `.tooltip('show')`, `.tooltip('hide')` and `.tooltip('toggle')` methods; this value cannot be combined with any other trigger. `'hover'` on its own will result in tooltips that cannot be triggered via the keyboard, and should only be used if alternative methods for conveying the same information for keyboard users is present. |
</BsTable>
@ -199,18 +176,6 @@ Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` opt
Options for individual tooltips can alternatively be specified through the use of data attributes, as explained above.
</Callout>
#### Using function with `popperConfig`
```js
const tooltip = new bootstrap.Tooltip(element, {
popperConfig(defaultBsPopperConfig) {
// const newPopperConfig = {...}
// use defaultBsPopperConfig if needed...
// return newPopperConfig
}
})
```
### Methods
<Callout name="danger-async-methods" type="danger" />
@ -218,17 +183,17 @@ const tooltip = new bootstrap.Tooltip(element, {
<BsTable>
| Method | Description |
| --- | --- |
| `disable` | Removes the ability for an elements tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled. |
| `dispose` | Hides and destroys an elements tooltip (Removes stored data on the DOM element). Tooltips that use delegation (which are created using [the `selector` option](#options)) cannot be individually destroyed on descendant trigger elements. |
| `enable` | Gives an elements tooltip the ability to be shown. **Tooltips are enabled by default.** |
| `disable` | Removes the ability for an element's tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled. |
| `dispose` | Hides and destroys an element's tooltip (Removes stored data on the DOM element). Tooltips that use delegation (which are created using [the `selector` option](#options)) cannot be individually destroyed on descendant trigger elements. |
| `enable` | Gives an element's tooltip the ability to be shown. **Tooltips are enabled by default.** |
| `getInstance` | *Static* method which allows you to get the tooltip instance associated with a DOM element. |
| `getOrCreateInstance` | *Static* method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case it wasnt initialized. |
| `hide` | Hides an elements tooltip. **Returns to the caller before the tooltip has actually been hidden** (i.e. before the `hidden.bs.tooltip` event occurs). This is considered a “manual” triggering of the tooltip. |
| `setContent` | Gives a way to change the tooltips content after its initialization. |
| `show` | Reveals an elements tooltip. **Returns to the caller before the tooltip has actually been shown** (i.e. before the `shown.bs.tooltip` event occurs). This is considered a “manual” triggering of the tooltip. Tooltips with zero-length titles are never displayed. |
| `toggle` | Toggles an elements tooltip. **Returns to the caller before the tooltip has actually been shown or hidden** (i.e. before the `shown.bs.tooltip` or `hidden.bs.tooltip` event occurs). This is considered a “manual” triggering of the tooltip. |
| `toggleEnabled` | Toggles the ability for an elements tooltip to be shown or hidden. |
| `update` | Updates the position of an elements tooltip. |
| `getOrCreateInstance` | *Static* method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case it wasn't initialized. |
| `hide` | Hides an element's tooltip. **Returns to the caller before the tooltip has actually been hidden** (i.e. before the `hidden.bs.tooltip` event occurs). This is considered a "manual" triggering of the tooltip. |
| `setContent` | Gives a way to change the tooltip's content after its initialization. |
| `show` | Reveals an element's tooltip. **Returns to the caller before the tooltip has actually been shown** (i.e. before the `shown.bs.tooltip` event occurs). This is considered a "manual" triggering of the tooltip. Tooltips with zero-length titles are never displayed. |
| `toggle` | Toggles an element's tooltip. **Returns to the caller before the tooltip has actually been shown or hidden** (i.e. before the `shown.bs.tooltip` or `hidden.bs.tooltip` event occurs). This is considered a "manual" triggering of the tooltip. |
| `toggleEnabled` | Toggles the ability for an element's tooltip to be shown or hidden. |
| `update` | Updates the position of an element's tooltip. |
</BsTable>
```js