Buuka ku bigambo ebikulu Buuka ku docs navigation
Check
in English

JavaScript

Leeta Bootstrap mu bulamu ne JavaScript plugins zaffe ez'okwesalirawo. Manya ebikwata ku buli plugin, data yaffe ne programmatic API options, n'ebirala.

Kinoomu oba ekikuŋŋaanyiziddwa

Plugins zisobola okuteekebwamu kinnoomu (nga okozesa Bootstrap's individual js/dist/*.js), oba zonna omulundi gumu nga okozesa bootstrap.jsoba ezikendeezeddwa bootstrap.min.js(tossaamu byombi).

Bw’oba ​​okozesa bundler (Webpack, Parcel, Vite...), osobola okukozesa /js/dist/*.jsfayiro eziri nga ziwedde ku UMD.

Enkozesa n'ensengeka za JavaScript

Wadde nga Bootstrap CSS esobola okukozesebwa ne framework yonna, Bootstrap JavaScript tekwatagana mu bujjuvu ne JavaScript frameworks nga React, Vue, ne Angular ezitwala okumanya okujjuvu ku DOM. Bootstrap ne framework zombi ziyinza okugezaako okukyusa ekintu kye kimu ekya DOM, ekivaamu obuzibu nga dropdowns ezisibira mu kifo “ekiggule”.

Enkola esinga obulungi eri abo abakozesa enkola ey’ekika kino kwe kukozesa enkola eyeetongodde mu kifo kya Bootstrap JavaScript. Wano waliwo ebimu ku bisinga okwettanirwa:

Okukozesa Bootstrap nga module

Ggwe kennyini kigezeeko! Wano wefunire source code ne demo ekola olw'okukozesa Bootstrap nga ES module okuva mu twbs/examples repository . Osobola n'okuggulawo ekyokulabirako mu StackBlitz .

Tuwa enkyusa ya Bootstrap ezimbiddwa nga ESM( bootstrap.esm.jsne bootstrap.esm.min.js) ekusobozesa okukozesa Bootstrap nga module mu browser, singa browser zo z'ogenderera zigiwagira .

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

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

Bw’ogeraageranya ne JS bundlers, okukozesa ESM mu browser kyetaagisa okukozesa ekkubo erijjuvu n’erinnya lya fayiro mu kifo ky’erinnya lya modulo. Soma ebisingawo ku modulo za JS mu browser. Eno y'ensonga lwaki tukozesa 'bootstrap.esm.min.js'mu kifo ky'okubeera 'bootstrap'waggulu. Naye kino kyongera okukaluba olw’okwesigamira kwaffe okwa Popper, okuyingiza Popper mu JavaScript yaffe nga bwe kiri:

import * as Popper from "@popperjs/core"

Bw'ogezaako kino nga bwe kiri, ojja kulaba ensobi mu console nga eno wammanga:

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

Okutereeza kino, osobola okukozesa an importmapokugonjoola amannya ga modulo agatali ga bulijjo okumaliriza amakubo. Singa browser zo z'ogenderera teziwagira importmap, ojja kwetaaga okukozesa pulojekiti ya es-module-shims . Laba engeri gye kikola ku Bootstrap ne Popper:

<!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>

Ebisinziirwako

Plugins ezimu n'ebitundu bya CSS byesigamye ku plugins endala. Bw'oba ossaamu plugins kinnoomu, kakasa nti okebera bino ebisinziirako mu docs.

Ebitundu byaffe ebigwa, popovers, n'ebikozesebwa nabyo byesigamye ku Popper .

Ebintu ebikwata ku data

Kumpi plugins zonna eza Bootstrap zisobola okusobozesa n’okusengekebwa okuyita mu HTML yokka nga zirina data attributes (engeri gye twagala okukozesaamu enkola ya JavaScript). Kakasa nti okozesa ekibinja kimu kyokka eky'ebintu bya data ku elementi emu (okugeza, tosobola kutandika tooltip ne modal okuva ku button y'emu.)

Nga eby'okulonda bwe bisobola okuyisibwa nga biyita mu bikwata ku data oba JavaScript, osobola okugattako erinnya ly'okulonda ku data-bs-, nga mu data-bs-animation="{value}". Kakasa nti okyusa ekika kya case eky’erinnya ly’okulonda okuva ku “ camelCase ” okudda ku “ kebab-case ” ng’oyisa eby’okulonda ng’oyita mu data attributes. Okugeza, kozesa data-bs-custom-class="beautifier"mu kifo kya data-bs-customClass="beautifier".

Okuva ku Bootstrap 5.2.0, ebitundu byonna biwagira ekintu kya data ekiterekeddwa eky'okugezesadata-bs-config ekiyinza okuteeka ensengeka y'ebitundu ennyangu ng'olunyiriri lwa JSON. Ekintu bwe kiba data-bs-config='{"delay":0, "title":123}'n'ebintu data-bs-title="456", omuwendo ogusembayo titlegujja kuba 456era ebifaananyi bya data eby'enjawulo bijja kusazaamu emiwendo egyaweebwa ku data-bs-config. Okugatta ku ekyo, ebikwata ku data ebiriwo bisobola okuteeka emiwendo gya JSON nga data-bs-delay='{"show":0,"hide":150}'.

Abasunsula

Tukozesa enzaaliranwa querySelectorn'enkola querySelectorAllokubuuza ebintu bya DOM olw'ensonga z'okukola, kale olina okukozesa ebisunsula ebituufu . Bw’oba ​​okozesa selectors ez’enjawulo nga collapse:Example, kakasa nti ozitoloka.

Ebibaddewo

Bootstrap egaba ebibaddewo eby'enjawulo ku bikolwa eby'enjawulo ebya plugins ebisinga obungi. Okutwalira awamu, bino bijja mu ngeri etaliiko nkomerero n’ennyiriri eziyise - nga ekintu ekitaliiko nkomerero (ex. show) kitandikibwawo ku ntandikwa y’ekintu ekibaawo, ate engeri yaakyo ey’ekitundu ekiyise (ex. shown) n’etandika nga ekikolwa kiwedde.

Ebintu byonna ebibaawo ebitaliiko nkomerero biwa preventDefault()enkola. Kino kiwa obusobozi okuyimiriza okukola ekikolwa nga tekinnatandika. Okuzzaayo false okuva ku event handler nakyo kijja kuyita otomatika preventDefault().

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

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

API ya pulogulaamu

Abazimbi bonna bakkiriza ekintu eky'okulonda eky'okwesalirawo oba tewali kintu kyonna (ekitandika plugin n'enneeyisa yaayo eya bulijjo):

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

Bw’oba ​​oyagala okufuna ekifaananyi kya plugin ekimu, buli plugin eraga getInstanceenkola. Okugeza, okuggya ekifaananyi butereevu okuva mu elementi:

bootstrap.Popover.getInstance(myPopoverEl)

Enkola eno ejja kudda nullsinga ekifaananyi tekitandikibwa ku kintu ekisabiddwa.

Ekirala, getOrCreateInstanceesobola okukozesebwa okufuna ekifaananyi ekikwatagana n'ekintu kya DOM, oba okukola ekipya mu mbeera nga tekitandikibwawo.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Mu mbeera nga ekifaananyi tekyatandikibwawo, kiyinza okukkiriza n'okukozesa ekintu eky'okusengeka eky'okwesalirawo ng'ensonga eyokubiri.

Ebilonda bya CSS mu bizimbisibwa

Ng’oggyeeko enkola getInstancene getOrCreateInstance, abazimbi bonna aba plugin basobola okukkiriza ekintu kya DOM oba ekisunsula kya CSS ekituufu ng’ensonga esooka. Plugin elements zisangibwa querySelectorn'enkola okuva plugins zaffe bwe ziwagira element emu yokka.

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')

Emirimu egitakwatagana n’enkyukakyuka

Enkola zonna eza programmatic API zibeera asynchronous era zidda eri oyo ayita oluvannyuma lw'enkyukakyuka okutandika, naye nga tennaggwa . Okusobola okukola ekikolwa ng’enkyukakyuka ewedde, osobola okuwuliriza ekintu ekikwatagana.

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

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

Okugatta ku ekyo, okuyita enkola ku kitundu ekikyukakyuka kujja kubuusibwa amaaso .

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 !!

disposeengeri

Wadde nga kiyinza okulabika ng’ekituufu okukozesa disposeenkola eno amangu ddala nga hide(), kijja kuleetera ebivaamu ebitali bituufu. Wano waliwo ekyokulabirako ky’enkozesa y’ekizibu:

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

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

Enteekateeka ezisookerwako

Osobola okukyusa ensengeka ezisookerwako eza plugin nga okyusa Constructor.Defaultekintu kya plugin:

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

Enkola n’eby’obugagga

Buli Bootstrap plugin eraga enkola zino wammanga n’ebintu ebitali bikyukakyuka.

Engeri Okunnyonnyola
dispose Esaanyaawo modal ya elementi. (Eggyawo data eterekeddwa ku elementi ya DOM)
getInstance Enkola ya static ekusobozesa okufuna modal instance ekwatagana ne DOM element.
getOrCreateInstance Enkola ya static ekusobozesa okufuna modal instance ekwatagana ne DOM element, oba okukola empya mu mbeera nga teyali etandikibwawo.
Eky’obugagga ekitali kikyukakyuka Okunnyonnyola
NAME Ezzaayo erinnya lya plugin. (Ekyokulabirako: bootstrap.Tooltip.NAME) .
VERSION Enkyusa ya buli emu ku plugins za Bootstrap esobola okuyingizibwa ng'oyita mu VERSIONkintu ky'omuzimbi wa plugin (Ekyokulabirako: bootstrap.Tooltip.VERSION) .

Eddagala erirongoosa

Tooltips ne Popovers zikozesa sanitizer yaffe ezimbiddwa mu sanitize options ezikkiriza HTML.

Omuwendo ogusookerwako allowListgwe guno wammanga:

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: []
}

Bw'oba oyagala okwongera emiwendo emipya ku kino ekisookerwako allowListosobola okukola bino wammanga:

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)

Bw’oba ​​oyagala okuyita ku sanitizer yaffe kubanga oyagala nnyo okukozesa etterekero ly’ebitabo eriweereddwayo, okugeza DOMPurify , olina okukola bino wammanga:

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

Okwesalirawo ng’okozesa jQuery

Teweetaaga jQuery mu Bootstrap 5 , naye kikyasoboka okukozesa ebitundu byaffe ne jQuery. Singa Bootstrap ezuula jQuerymu windowkintu, ejja kwongerako ebitundu byaffe byonna mu nkola ya jQuery eya plugin. Kino kikusobozesa okukola bino wammanga:

$('[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

Bwe kityo bwe kiri ne ku bitundu byaffe ebirala.

Tewali butakkaanya

Oluusi kyetaagisa okukozesa Bootstrap plugins ne UI frameworks endala. Mu mbeera zino, okutomeragana kw'ekifo ky'amannya kuyinza okubaawo oluusi n'oluusi. Kino bwe kibaawo, oyinza okuyita .noConflictku plugin gy’oyagala okuzzaawo omuwendo gwayo.

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

Bootstrap tewagira mu butongole tterekero lya JavaScript ery'ekibiina eky'okusatu nga Prototype oba jQuery UI. Wadde nga waliwo .noConflictebibaddewo nga biteekeddwa mu kifo ky’amannya, wayinza okubaawo ebizibu by’okukwatagana by’olina okutereeza ku bubwo.

jEbibaawo mu kubuuza

Bootstrap ejja kuzuula jQuery singa jQueryebaawo mu windowkintu era nga tewali data-bs-no-jqueryattribute eteekeddwa ku <body>. Singa jQuery esangibwa, Bootstrap ejja kufulumya ebibaddewo olw'enkola y'ebibaddewo eya jQuery. Kale bw'oba oyagala okuwuliriza ebibaawo mu Bootstrap, ojja kuba olina okukozesa enkola za jQuery ( .on, .one) mu kifo kya addEventListener.

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

JavaScript eremeddwa okukola

Plugin za Bootstrap tezirina fallback ya njawulo nga JavaScript eremeddwa. Bw’oba ​​ofaayo ku bumanyirivu bw’omukozesa mu mbeera eno, kozesa <noscript>okunnyonnyola embeera (n’engeri y’okuddamu okusobozesa JavaScript) eri abakozesa bo, ne/oba okwongerako ebikuddirira byo eby’ennono.