0
0
mirror of https://github.com/twbs/bootstrap.git synced 2024-11-30 12:24:19 +01:00
Bootstrap/site/content/docs/4.3/getting-started/javascript.md

230 lines
9.1 KiB
Markdown
Raw Normal View History

2014-07-12 11:20:15 +02:00
---
layout: docs
2015-04-05 08:31:41 +02:00
title: JavaScript
description: Bring Bootstrap to life with our optional JavaScript plugins. Learn about each plugin, our data and programmatic API options, and more.
group: getting-started
toc: true
2014-07-12 11:20:15 +02:00
---
2015-05-29 10:58:52 +02:00
## Individual or compiled
2014-03-17 03:03:53 +01:00
Plugins can be included individually (using Bootstrap's individual `js/dist/*.js`), or all at once using `bootstrap.js` or the minified `bootstrap.min.js` (don't include both).
If you use a bundler (Webpack, Rollup...), you can use `/js/dist/*.js` files which are UMD ready.
2014-07-12 11:45:15 +02:00
## Using Bootstrap as a module
We provide a version of Bootstrap built as `ESM` (`bootstrap.esm.js` and `bootstrap.esm.min.js`) which allows you to use Bootstrap as a module in your browser, if your [targeted browsers support it](https://caniuse.com/#feat=es6-module).
{{< highlight html >}}
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
{{< /highlight >}}
{{< callout warning >}}
## Incompatible plugins
Due to browser limitations, some of our plugins, namely Dropdown, Tooltip and Popover plugins, cannot be used in a `<script>` tag with `module` type because they depend on Popper.js. For more information about the issue see [here](https://developers.google.com/web/fundamentals/primers/modules#specifiers).
{{< /callout >}}
2015-05-29 10:58:52 +02:00
## Dependencies
2014-07-12 11:45:15 +02:00
Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs.
Our dropdowns, popovers and tooltips also depend on [Popper.js](https://popper.js.org/).
2014-03-17 03:03:53 +01:00
2019-08-04 12:30:29 +02:00
## Still want to use jQuery? It's possible!
2019-08-04 12:30:29 +02:00
Bootstrap 5 is designed to be used without jQuery, but it's still possible to use our components with jQuery. **If Bootstrap detects `jQuery` in the `window` object** it'll add all of our components in jQuery's plugin system; this means you'll be able to do `$('[data-toggle="tooltip"]').tooltip()` to enable tooltips. The same goes for our other components.
2015-05-29 10:58:52 +02:00
## Data attributes
2014-03-17 03:03:53 +01:00
2015-03-09 16:35:45 +01:00
Nearly all Bootstrap plugins can be enabled and configured through HTML alone with data attributes (our preferred way of using JavaScript functionality). Be sure to **only use one set of data attributes on a single element** (e.g., you cannot trigger a tooltip and modal from the same button.)
2014-03-17 03:03:53 +01:00
{{< callout warning >}}
## Selectors
Currently to query DOM elements we use the native methods `querySelector` and `querySelectorAll` for performance reasons, so you have to use [valid selectors](https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier).
If you use special selectors, for example: `collapse:Example` be sure to escape them.
{{< /callout >}}
## Events
Bootstrap provides custom events for most plugins' unique actions. Generally, these come in an infinitive and past participle form - where the infinitive (ex. `show`) is triggered at the start of an event, and its past participle form (ex. `shown`) is triggered on the completion of an action.
2017-06-17 03:59:43 +02:00
All infinitive events provide [`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) functionality. This provides the ability to stop the execution of an action before it starts. Returning false from an event handler will also automatically call `preventDefault()`.
{{< highlight js >}}
var myModal = document.getElementById('myModal')
myModal.addEventListener('show.bs.modal', function (e) {
if (!data) {
return e.preventDefault() // stops modal from being shown
}
})
{{< /highlight >}}
2019-07-31 22:05:24 +02:00
{{< callout warning >}}
## jQuery events
2019-08-02 16:24:07 +02:00
Bootstrap will detect jQuery if `jQuery` is present in the `window` object and there is no `data-no-jquery` attribute set on `<body>`. If jQuery is found, Bootstrap will emit events thanks to jQuery's event system. So if you want to listen to Bootstrap's events, you'll have to use the jQuery methods (`.on`, `.one`) instead of `addEventListener`.
2019-07-31 22:05:24 +02:00
{{< highlight js >}}
$('#myTab a').on('shown.bs.tab', function () {
// do something...
})
{{< /highlight >}}
{{< /callout >}}
2015-05-29 10:58:52 +02:00
## Programmatic API
2014-07-12 11:45:15 +02:00
All constructors accept an optional options object or nothing (which initiates a plugin with its default behavior):
2014-07-12 11:45:15 +02:00
{{< highlight js >}}
var myModalEl = document.getElementById('myModal')
2014-07-12 11:45:15 +02:00
var modal = new bootstrap.Modal(myModalEl) // initialized with defaults
var modal = new bootstrap.Modal(myModalEl, { keyboard: false }) // initialized with no keyboard
{{< /highlight >}}
2014-03-17 03:03:53 +01:00
2019-07-28 15:24:46 +02:00
If you'd like to get a particular plugin instance, each plugin exposes a `getInstance` method. In order to retrieve it directly from an element, do this: `bootstrap.Popover.getInstance(myPopoverEl)`.
2014-07-12 11:45:15 +02:00
### Asynchronous functions and transitions
2018-09-16 20:02:30 +02:00
All programmatic API methods are **asynchronous** and return to the caller once the transition is started but **before it ends**.
In order to execute an action once the transition is complete, you can listen to the corresponding event.
{{< highlight js >}}
var myCollapseEl = document.getElementById('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', function (e) {
// Action to execute once the collapsible area is expanded
})
{{< /highlight >}}
In addition a method call on a **transitioning component will be ignored**.
{{< highlight js >}}
var myCarouselEl = document.getElementById('myCarousel')
2019-07-28 15:24:46 +02:00
var carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance
myCarouselEl.addEventListener('slid.bs.carousel', function (e) {
carousel.to('2') // Will slide to the slide 2 as soon as the transition to slide 1 is finished
})
2014-07-12 11:45:15 +02:00
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 !!
{{< /highlight >}}
### Default settings
2017-09-26 13:50:35 +02:00
You can change the default settings for a plugin by modifying the plugin's `Constructor.Default` object:
2014-03-17 03:03:53 +01:00
{{< highlight js >}}
2019-02-10 21:25:51 +01:00
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
{{< /highlight >}}
2014-03-17 03:03:53 +01:00
## No conflict (only if you use jQuery)
2014-07-12 11:45:15 +02:00
Sometimes it is necessary to use Bootstrap plugins with other UI frameworks. In these circumstances, namespace collisions can occasionally occur. If this happens, you may call `.noConflict` on the plugin you wish to revert the value of.
2014-07-12 11:45:15 +02:00
{{< highlight js >}}
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
2019-02-10 21:25:51 +01:00
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
{{< /highlight >}}
2014-03-17 03:03:53 +01:00
2015-05-29 10:58:52 +02:00
## Version numbers
Merge branch 'master' into v4 Conflicts: Gruntfile.js dist/css/bootstrap-theme.css dist/css/bootstrap-theme.css.map dist/css/bootstrap-theme.min.css dist/css/bootstrap.css dist/css/bootstrap.css.map dist/css/bootstrap.min.css dist/js/bootstrap.min.js docs/_data/glyphicons.yml docs/_includes/components/alerts.html docs/_includes/components/badges.html docs/_includes/components/breadcrumbs.html docs/_includes/components/button-dropdowns.html docs/_includes/components/button-groups.html docs/_includes/components/dropdowns.html docs/_includes/components/glyphicons.html docs/_includes/components/input-groups.html docs/_includes/components/jumbotron.html docs/_includes/components/labels.html docs/_includes/components/list-group.html docs/_includes/components/media.html docs/_includes/components/navbar.html docs/_includes/components/navs.html docs/_includes/components/page-header.html docs/_includes/components/pagination.html docs/_includes/components/panels.html docs/_includes/components/progress-bars.html docs/_includes/components/responsive-embed.html docs/_includes/components/thumbnails.html docs/_includes/components/wells.html docs/_includes/css/buttons.html docs/_includes/css/code.html docs/_includes/css/forms.html docs/_includes/css/grid.html docs/_includes/css/helpers.html docs/_includes/css/images.html docs/_includes/css/less.html docs/_includes/css/tables.html docs/_includes/css/type.html docs/_includes/customizer-variables.html docs/_includes/getting-started/accessibility.html docs/_includes/getting-started/disabling-responsiveness.html docs/_includes/getting-started/download.html docs/_includes/getting-started/whats-included.html docs/_includes/js/alerts.html docs/_includes/js/buttons.html docs/_includes/js/carousel.html docs/_includes/js/collapse.html docs/_includes/js/modal.html docs/_includes/js/overview.html docs/_includes/js/popovers.html docs/_includes/js/tabs.html docs/_includes/js/tooltips.html docs/_includes/nav/components.html docs/_includes/nav/javascript.html docs/_jade/customizer-variables.jade docs/_layouts/default.html docs/about.html docs/assets/css/docs.min.css docs/assets/css/src/docs.css docs/assets/js/customize.min.js docs/assets/js/raw-files.min.js docs/assets/js/src/customizer.js docs/customize.html docs/dist/css/bootstrap-theme.css.map docs/dist/css/bootstrap.css docs/dist/css/bootstrap.css.map docs/dist/css/bootstrap.min.css less/glyphicons.less less/mixins/vendor-prefixes.less less/navbar.less less/popovers.less less/tables.less less/theme.less less/tooltip.less less/variables.less package.json scss/_carousel.scss scss/_close.scss scss/_forms.scss test-infra/npm-shrinkwrap.json
2015-01-04 05:08:58 +01:00
The version of each of Bootstrap's plugins can be accessed via the `VERSION` property of the plugin's constructor. For example, for the tooltip plugin:
Merge branch 'master' into v4 Conflicts: Gruntfile.js dist/css/bootstrap-theme.css dist/css/bootstrap-theme.css.map dist/css/bootstrap-theme.min.css dist/css/bootstrap.css dist/css/bootstrap.css.map dist/css/bootstrap.min.css dist/js/bootstrap.min.js docs/_data/glyphicons.yml docs/_includes/components/alerts.html docs/_includes/components/badges.html docs/_includes/components/breadcrumbs.html docs/_includes/components/button-dropdowns.html docs/_includes/components/button-groups.html docs/_includes/components/dropdowns.html docs/_includes/components/glyphicons.html docs/_includes/components/input-groups.html docs/_includes/components/jumbotron.html docs/_includes/components/labels.html docs/_includes/components/list-group.html docs/_includes/components/media.html docs/_includes/components/navbar.html docs/_includes/components/navs.html docs/_includes/components/page-header.html docs/_includes/components/pagination.html docs/_includes/components/panels.html docs/_includes/components/progress-bars.html docs/_includes/components/responsive-embed.html docs/_includes/components/thumbnails.html docs/_includes/components/wells.html docs/_includes/css/buttons.html docs/_includes/css/code.html docs/_includes/css/forms.html docs/_includes/css/grid.html docs/_includes/css/helpers.html docs/_includes/css/images.html docs/_includes/css/less.html docs/_includes/css/tables.html docs/_includes/css/type.html docs/_includes/customizer-variables.html docs/_includes/getting-started/accessibility.html docs/_includes/getting-started/disabling-responsiveness.html docs/_includes/getting-started/download.html docs/_includes/getting-started/whats-included.html docs/_includes/js/alerts.html docs/_includes/js/buttons.html docs/_includes/js/carousel.html docs/_includes/js/collapse.html docs/_includes/js/modal.html docs/_includes/js/overview.html docs/_includes/js/popovers.html docs/_includes/js/tabs.html docs/_includes/js/tooltips.html docs/_includes/nav/components.html docs/_includes/nav/javascript.html docs/_jade/customizer-variables.jade docs/_layouts/default.html docs/about.html docs/assets/css/docs.min.css docs/assets/css/src/docs.css docs/assets/js/customize.min.js docs/assets/js/raw-files.min.js docs/assets/js/src/customizer.js docs/customize.html docs/dist/css/bootstrap-theme.css.map docs/dist/css/bootstrap.css docs/dist/css/bootstrap.css.map docs/dist/css/bootstrap.min.css less/glyphicons.less less/mixins/vendor-prefixes.less less/navbar.less less/popovers.less less/tables.less less/theme.less less/tooltip.less less/variables.less package.json scss/_carousel.scss scss/_close.scss scss/_forms.scss test-infra/npm-shrinkwrap.json
2015-01-04 05:08:58 +01:00
{{< highlight js >}}
bootstrap.Tooltip.VERSION // => "{{< param current_version >}}"
{{< /highlight >}}
Merge branch 'master' into v4 Conflicts: Gruntfile.js dist/css/bootstrap-theme.css dist/css/bootstrap-theme.css.map dist/css/bootstrap-theme.min.css dist/css/bootstrap.css dist/css/bootstrap.css.map dist/css/bootstrap.min.css dist/js/bootstrap.min.js docs/_data/glyphicons.yml docs/_includes/components/alerts.html docs/_includes/components/badges.html docs/_includes/components/breadcrumbs.html docs/_includes/components/button-dropdowns.html docs/_includes/components/button-groups.html docs/_includes/components/dropdowns.html docs/_includes/components/glyphicons.html docs/_includes/components/input-groups.html docs/_includes/components/jumbotron.html docs/_includes/components/labels.html docs/_includes/components/list-group.html docs/_includes/components/media.html docs/_includes/components/navbar.html docs/_includes/components/navs.html docs/_includes/components/page-header.html docs/_includes/components/pagination.html docs/_includes/components/panels.html docs/_includes/components/progress-bars.html docs/_includes/components/responsive-embed.html docs/_includes/components/thumbnails.html docs/_includes/components/wells.html docs/_includes/css/buttons.html docs/_includes/css/code.html docs/_includes/css/forms.html docs/_includes/css/grid.html docs/_includes/css/helpers.html docs/_includes/css/images.html docs/_includes/css/less.html docs/_includes/css/tables.html docs/_includes/css/type.html docs/_includes/customizer-variables.html docs/_includes/getting-started/accessibility.html docs/_includes/getting-started/disabling-responsiveness.html docs/_includes/getting-started/download.html docs/_includes/getting-started/whats-included.html docs/_includes/js/alerts.html docs/_includes/js/buttons.html docs/_includes/js/carousel.html docs/_includes/js/collapse.html docs/_includes/js/modal.html docs/_includes/js/overview.html docs/_includes/js/popovers.html docs/_includes/js/tabs.html docs/_includes/js/tooltips.html docs/_includes/nav/components.html docs/_includes/nav/javascript.html docs/_jade/customizer-variables.jade docs/_layouts/default.html docs/about.html docs/assets/css/docs.min.css docs/assets/css/src/docs.css docs/assets/js/customize.min.js docs/assets/js/raw-files.min.js docs/assets/js/src/customizer.js docs/customize.html docs/dist/css/bootstrap-theme.css.map docs/dist/css/bootstrap.css docs/dist/css/bootstrap.css.map docs/dist/css/bootstrap.min.css less/glyphicons.less less/mixins/vendor-prefixes.less less/navbar.less less/popovers.less less/tables.less less/theme.less less/tooltip.less less/variables.less package.json scss/_carousel.scss scss/_close.scss scss/_forms.scss test-infra/npm-shrinkwrap.json
2015-01-04 05:08:58 +01:00
2015-05-29 10:58:52 +02:00
## No special fallbacks when JavaScript is disabled
Merge branch 'master' into derp Conflicts: _config.yml dist/css/bootstrap-theme.css.map dist/css/bootstrap.css dist/css/bootstrap.css.map dist/css/bootstrap.min.css docs/_includes/components/glyphicons.html docs/_includes/css/forms.html docs/_includes/css/tables.html docs/_includes/getting-started/browser-device-support.html docs/_includes/header.html docs/_includes/js/affix.html docs/_includes/js/alerts.html docs/_includes/js/buttons.html docs/_includes/js/dropdowns.html docs/_includes/js/overview.html docs/_includes/js/popovers.html docs/_includes/js/tooltips.html docs/_includes/nav/javascript.html docs/assets/css/docs.min.css docs/assets/css/src/docs.css docs/assets/js/customize.min.js docs/assets/js/docs.min.js docs/assets/js/raw-files.min.js docs/browser-bugs.html docs/dist/css/bootstrap-theme.css.map docs/dist/css/bootstrap.css docs/dist/css/bootstrap.css.map docs/dist/css/bootstrap.min.css docs/examples/blog/index.html docs/examples/carousel/index.html docs/examples/cover/index.html docs/examples/dashboard/index.html docs/examples/grid/index.html docs/examples/jumbotron-narrow/index.html docs/examples/jumbotron/index.html docs/examples/justified-nav/index.html docs/examples/navbar-fixed-top/index.html docs/examples/navbar-static-top/index.html docs/examples/navbar/index.html docs/examples/non-responsive/index.html docs/examples/offcanvas/index.html docs/examples/signin/index.html docs/examples/starter-template/index.html docs/examples/sticky-footer-navbar/index.html docs/examples/sticky-footer/index.html docs/examples/theme/index.html docs/examples/tooltip-viewport/index.html less/code.less less/panels.less less/variables.less
2014-08-03 03:30:59 +02:00
Bootstrap's plugins don't fall back particularly gracefully when JavaScript is disabled. If you care about the user experience in this case, use [`<noscript>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript) to explain the situation (and how to re-enable JavaScript) to your users, and/or add your own custom fallbacks.
{{< callout warning >}}
##### Third-party libraries
**Bootstrap does not officially support third-party JavaScript libraries** like Prototype or jQuery UI. Despite `.noConflict` and namespaced events, there may be compatibility problems that you need to fix on your own.
{{< /callout >}}
## Sanitizer
Tooltips and Popovers use our built-in sanitizer to sanitize options which accept HTML.
The default `whiteList` value is the following:
{{< highlight js >}}
var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
var DefaultWhitelist = {
// 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', 'alt', 'title', 'width', 'height'],
li: [],
ol: [],
p: [],
pre: [],
s: [],
small: [],
span: [],
sub: [],
sup: [],
strong: [],
u: [],
ul: []
}
{{< /highlight >}}
If you want to add new values to this default `whiteList` you can do the following:
{{< highlight js >}}
var myDefaultWhiteList = bootstrap.Tooltip.Default.whiteList
// To allow table elements
myDefaultWhiteList.table = []
// To allow td elements and data-option attributes on td elements
myDefaultWhiteList.td = ['data-option']
// You can push your custom regex to validate your attributes.
// Be careful about your regular expressions being too lax
var myCustomRegex = /^data-my-app-[\w-]+/
myDefaultWhiteList['*'].push(myCustomRegex)
{{< /highlight >}}
If you want to bypass our sanitizer because you prefer to use a dedicated library, for example [DOMPurify](https://www.npmjs.com/package/dompurify), you should do the following:
{{< highlight js >}}
var yourTooltipEl = document.getElementById('yourTooltip')
var tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn: function (content) {
return DOMPurify.sanitize(content)
}
})
{{< /highlight >}}