Main content ah kal rawh Docs navigation ah kal rawh
Check
in English

JavaScript hmangin a rawn lang ang

Kan optional JavaScript plugins hmangin Bootstrap chu nunna pe rawh. Plugin tin chungchang te, kan data leh programmatic API option te leh thil dang tam tak zir rawh.

Mimal emaw, khawlkhawm emaw a ni thei

Plugins chu pakhat zel hmangin (Bootstrap’s individual hmangin js/dist/*.js), a nih loh leh vawi khatah hmang vek bootstrap.jsemaw, minified emaw hmangin bootstrap.min.js(a pahnih hian telh loh tur) te pawh a tel thei bawk.

Bundler (Webpack, Parcel, Vite...) i hman chuan /js/dist/*.jsUMD ready file i hmang thei ang.

JavaScript framework hmanga hman dan

Bootstrap CSS hi framework eng pawh nen hman theih a nih laiin, Bootstrap JavaScript hi JavaScript framework React, Vue, leh Angular ang chi DOM hriatna famkim anga ngaihte nen a inmil tawk lo hle. Bootstrap leh framework pahnih hian DOM element pakhat chu mutate an tum thei a, chu chuan dropdown ang chi bug te chu “open” position-ah a tlakbuak thei a ni.

Hetiang framework hmangtute tan chuan a tha zawk chu Bootstrap JavaScript hmang lovin framework-specific package hman hi a ni. Hetah hian duhthlan tur lar ber berte chu hetiang hi a ni:

Bootstrap chu module atan hman a ni

Nangmah ngeiin han ti ve teh! Bootstrap chu ES module atana hman tur source code leh working demo chu twbs/examples repository atangin download rawh . StackBlitz ah pawh entirnan i hawng thei bawk .

Bootstrap version ESM( bootstrap.esm.jsleh bootstrap.esm.min.js) anga siam kan pe a, chu chuan Bootstrap chu browser-ah module atan i hmang thei a, i target browser-te’n an support chuan

<script type="module">
  import { Toast } from 'bootstrap.esm.min.js'

  Array.from(document.querySelectorAll('.toast'))
    .forEach(toastNode => new Toast(toastNode))
</script>

JS bundler nena khaikhin chuan browser-a ESM hman hian module hming aiah full path leh filename hman a ngai a ni. JS module chungchang hi browser ah chhiar belh rawh. Chuvang chuan chunglam 'bootstrap.esm.min.js'aiah kan hmang a ni. 'bootstrap'Mahse, hei hi kan Popper dependency hian a ti buai zual sauh a, chu chuan Popper chu kan JavaScript-ah hetiang hian a import a ni:

import * as Popper from "@popperjs/core"

Hetiang ang hian i tih chuan console ah hian a hnuaia mi ang hian error i hmu ang:

Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".

Hei hi siamthat nan chuan an hmangin importmappaths tihfel nan arbitrary module hmingte chu resolve theih a ni. I target browser te hian , an support loh chuan es-module-shims project hi importmapi hmang a ngai ang . Bootstrap leh Popper tan a hnathawh dan chu hetiang hi a ni:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <title>Hello, modularity!</title>
  </head>
  <body>
    <h1>Hello, modularity!</h1>
    <button id="popoverButton" type="button" class="btn btn-primary btn-lg" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="ESM in Browser" data-bs-content="Bang!">Custom popover</button>

    <script async src="https://cdn.jsdelivr.net/npm/es-module-shims@1/dist/es-module-shims.min.js" crossorigin="anonymous"></script>
    <script type="importmap">
    {
      "imports": {
        "@popperjs/core": "https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js",
        "bootstrap": "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.esm.min.js"
      }
    }
    </script>
    <script type="module">
      import * as bootstrap from 'bootstrap'

      new bootstrap.Popover(document.getElementById('popoverButton'))
    </script>
  </body>
</html>

Innghahna te

Plugin leh CSS component thenkhat chu plugin dang a innghat a ni. Plugin te chu pakhat zel i dah tel a nih chuan docs ah hian heng dependencies te hi enfiah ngei ngei tur a ni.

Kan dropdowns, popovers, leh tooltips te pawh Popper ah a innghat bawk .

Data attribute te hi a ni

Bootstrap plugin zawng zawng deuhthaw hi HTML hmang chauhvin data attribute (JavaScript functionality hman dan kan duh ber) hmangin enable leh configure theih a ni. Element pakhatah data attribute set khat chauh hmang ngei ang che (eg, button pakhat atang hian tooltip leh modal i trigger thei lo.)

Options chu data attribute emaw JavaScript hmanga pass theih a nih avangin option hming chu data-bs-, ah hian i append thei ang data-bs-animation="{value}". Data attribute hmanga options pass dawnin option hming case type chu “ camelCase ” atanga “ kebab-case ” ah thlak ngei ngei tur a ni. Entirnan, data-bs-custom-class="beautifier"tih aiah hmang data-bs-customClass="beautifier"rawh.

Bootstrap 5.2.0 atang khan component zawng zawng hian experimental reserved data attribute an support data-bs-configa, chu chuan JSON string angin component configuration awlsam tak a dah thei a ni. Element pakhatin data-bs-config='{"delay":0, "title":123}'leh data-bs-title="456"attribute a neih chuan a tawp ber titlevalue chu a ni ang a 456, data attribute hrang hrangte chuan , a value pekte chu a override ang data-bs-config. Chu bakah, data attribute awmsa te hian JSON value te chu data-bs-delay='{"show":0,"hide":150}'.

Selector te pawh a awm

Performance avanga DOM elements query nan native querySelectorleh methods kan hmang a, chuvangin valid selectors i hmang tur a ni . Special selector ang chi i hman chuan tlanchhiatsan ngei ngei tur a ni.querySelectorAllcollapse:Example

Thil thlengte

Bootstrap hian plugin tam zawkte thiltih danglam bik atan custom event a pe a. A tlangpuiin, hengte hi infinitive leh past participle form-ah an lo kal a - chutah chuan showthilthleng pakhat tan tirh lamah infinitive (ex. ) chu a insiam a, a past participle form (ex. shown) chu thiltih zawh hunah a insiam a ni.

Infinitive event zawng zawng hian preventDefault()functionality an pe vek a. Hei hian action pakhat execution chu a tan hmaa tihtawp theihna a pe a ni. Event handler atanga false rawn thawn let pawhin automatic in a call ang preventDefault().

const myModal = document.querySelector('#myModal')

myModal.addEventListener('show.bs.modal', event => {
  if (!data) {
    return event.preventDefault() // stops modal from being shown
  }
})

Programmatic API hmanga siam a ni

Constructor zawng zawng hian optional options object emaw engmah an pawm lo (chu chuan plugin chu a default behavior nen a initiate a ni):

const myModalEl = document.querySelector('#myModal')

const modal = new bootstrap.Modal(myModalEl) // initialized with defaults

const configObject = { keyboard: false }
const modal1 = new bootstrap.Modal(myModalEl, configObject) // initialized with no keyboard

Plugin instance bik i hmuh duh chuan plugin tin hian getInstancemethod pakhat an expose vek a. Entirnan, element atanga instance direct-a lakchhuah tur chuan:

bootstrap.Popover.getInstance(myPopoverEl)

He method hi nullelement dil chunga instance initiate a nih loh chuan a rawn kir leh ang.

A dang pawhin, getOrCreateInstanceDOM element nena inzawm instance hmuh nan hman theih a ni a, initialized a nih loh chuan a thar siam theih a ni bawk.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Instance pakhat initialized a nih loh chuan optional configuration object chu second argument atan a pawm thei a, a hmang thei bawk.

Constructor hrang hrangah CSS selector te a awm

getInstanceand methods bakah hian getOrCreateInstanceplugin constructor zawng zawng hian DOM element emaw CSS selector dik tak emaw chu argument hmasa ber atan an pawm thei vek a ni. querySelectorKan plugins te hian element pakhat chauh an support avangin method nen hian plugin elements te hi hmuh tur a awm.

const modal = new bootstrap.Modal('#myModal')
const dropdown = new bootstrap.Dropdown('[data-bs-toggle="dropdown"]')
const offcanvas = bootstrap.Offcanvas.getInstance('#myOffcanvas')
const alert = bootstrap.Alert.getOrCreateInstance('#myAlert')

Asynchronous hnathawh leh inthlak danglamna te

Programmatic API method zawng zawng hi asynchronous a ni a, transition a tan veleh caller hnenah a kir leh a, mahse a tawp hmain . Transition zawh veleh action execute tur chuan a inmil event chu i ngaithla thei ang.

const myCollapseEl = document.querySelector('#myCollapse')

myCollapseEl.addEventListener('shown.bs.collapse', event => {
  // Action to execute once the collapsible area is expanded
})

Chu bakah, transitioning component-a method call chu ngaihthah a ni ang .

const myCarouselEl = document.querySelector('#myCarousel')
const carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance

myCarouselEl.addEventListener('slid.bs.carousel', event => {
  carousel.to('2') // Will slide to the slide 2 as soon as the transition to slide 1 is finished
})

carousel.to('1') // Will start sliding to the slide 1 and returns to the caller
carousel.to('2') // !! Will be ignored, as the transition to the slide 1 is not finished !!

disposetihdan

dispose, hnua hman nghal mai chu a dik angin a lang thei a hide(), mahse, a rah chhuah dik lo a thlen ang. Problem hman dan entir nan hetiang hi a ni:

const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous

myModal.addEventListener('shown.bs.hidden', event => {
  myModal.dispose()
})

Settings hmasa ber a ni

Plugin pakhat tana default settings chu plugin Constructor.Defaultobject chu siam danglamin i thlak thei ang:

// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false

Thiltih dan leh thil neih dan

Bootstrap plugin tin hian a hnuaia method leh static property te hi a pholang vek a.

Tihdan Hrilhfiahna
dispose Element pakhat modal a tichhia. (DOM element-a data dahkhawmte a paih chhuak)
getInstance Static method hmanga DOM element nena inzawm modal instance hmuh theihna tur.
getOrCreateInstance Static method hmanga DOM element nena inzawm modal instance hmuh theihna tur, a nih loh leh initialized a nih loh chuan a thar siam theihna tur.
Static property a ni Hrilhfiahna
NAME Plugin hming a rawn pe leh ang. (Entirnan: bootstrap.Tooltip.NAME) .
VERSION Bootstrap-a plugin tinte version chu VERSIONplugin-a constructor property hmangin a lut thei a (Entirna: bootstrap.Tooltip.VERSION) .

Sanitizer hman a ni

Tooltips leh Popovers te hian kan built-in sanitizer hmangin HTML pawmtu option te chu an sanitize thin.

Default allowListvalue chu a hnuaia mi ang hian a ni:

const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
const DefaultAllowlist = {
  // Global attributes allowed on any supplied element below.
  '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
  a: ['target', 'href', 'title', 'rel'],
  area: [],
  b: [],
  br: [],
  col: [],
  code: [],
  div: [],
  em: [],
  hr: [],
  h1: [],
  h2: [],
  h3: [],
  h4: [],
  h5: [],
  h6: [],
  i: [],
  img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],
  li: [],
  ol: [],
  p: [],
  pre: [],
  s: [],
  small: [],
  span: [],
  sub: [],
  sup: [],
  strong: [],
  u: [],
  ul: []
}

He default ah hian value thar i dah duh chuan allowLista hnuaia mi ang hian i ti thei ang:

const myDefaultAllowList = bootstrap.Tooltip.Default.allowList

// To allow table elements
myDefaultAllowList.table = []

// To allow td elements and data-bs-option attributes on td elements
myDefaultAllowList.td = ['data-bs-option']

// You can push your custom regex to validate your attributes.
// Be careful about your regular expressions being too lax
const myCustomRegex = /^data-my-app-[\w-]+/
myDefaultAllowList['*'].push(myCustomRegex)

Library bik hman i duh avangin kan sanitizer hi bypass i duh a nih chuan, entirnan DOMPurify , a hnuaia mi ang hian i ti tur a ni:

const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
  sanitizeFn(content) {
    return DOMPurify.sanitize(content)
  }
})

A duh chuan jQuery hmangin

Bootstrap 5 ah hian jQuery i mamawh lo a , mahse jQuery hmang hian kan component te hi hman theih a la ni tho. Bootstrap hian object jQueryah a detect a nih chuan windowjQuery plugin system ah kan component zawng zawng a add vek ang. Hei hian a hnuaia mi te hi i ti thei a ni:

$('[data-bs-toggle="tooltip"]').tooltip() // to enable tooltips, with default configuration

$('[data-bs-toggle="tooltip"]').tooltip({ boundary: 'clippingParents', customClass: 'myClass' }) // to initialize tooltips with given configuration

$('#myTooltip').tooltip('show') // to trigger `show` method

Kan component dangte pawh chutiang bawk chu a ni.

Inhnialna a awm lo

A chang chuan Bootstrap plugins te hi UI framework dang nen hman a ngai thin. Hetiang dinhmunah hian namespace collision a awm fo thin. Chutiang a nih chuan i .noConflictvalue revert duh plugin chu i call thei ang.

const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality

Bootstrap hian official takin third-party JavaScript library Prototype emaw jQuery UI ang chi a support lo. Despite .noConflictleh namespaced events, compatibility problem a awm thei a, chu chu nangmah ngeiin i siam that a ngai a ni.

jQuery thil thlengte

Bootstrap hian jQuery jQuerychu windowobject ah a awm a, data-bs-no-jqueryattribute set a awm loh chuan a detect ang <body>. jQuery hmuh a nih chuan Bootstrap hian jQuery-a event system vangin event a emit ang. Chuvangin Bootstrap-a events ngaihthlak duh chuan jQuery methods ( .on, .one) hmang lovin addEventListener.

$('#myTab a').on('shown.bs.tab', () => {
  // do something...
})

JavaScript tihkhawtlai a ni

Bootstrap-a plugins hian JavaScript tihtawp a nih chuan special fallback a nei lo. Hetiang a nih avang hian user experience i ngaih pawimawh a nih chuan, i user-te <noscript>hnena thil awmdan (leh JavaScript re-enable dan tur) hrilhfiah nan hmang la, leh/ emaw, nangmah ngeiin i custom fallback te pawh add rawh.