Use
Load from CDN
Thanks to jsdelivr we have a CDN link, so drop this line before your ending </body>
tag. Latest releases come here.
<script type="text/javascript" src="https://cdn.jsdelivr.net/bootstrap.native/1.0.2/bootstrap-native.min.js"></script>
As most of the scripts manipulate the DOM when ready, there is no need to include a document.ready
statement or link the script(s) in the <head>
. That's your first performance tip if you are new around here.
Working locally
If you host the file on your project folders, download the package at github, unpack it, copy the file from the dist/
folder into your application's assets folder, then simply drop this line (according to your application assets folders) before your ending </body>
tag.
<script type="text/javascript" src="../assets/js/bootstrap-native.min.js"></script>
Alternatively you can link individual scripts, exactly the scripts required for your specific page. The lib
folder comes with all scripts in both raw and minified distribution formats, perhaps you are using require.js or module loaders, check the next section.
npm, Bower, RequireJS, CommonJS
Thanks to Ingwie Phoenix, our scripts here can be easily loaded for npm
, Bower
, RequireJS
or CommonJS
, so if you are using a module loader, you can also use this package via require()
as well. Here's how to do it:
var bsn = require("bootstrap.native");
// Create a button:
var btn = new bsn.Button(...);
This package can be installed using npm
or Bower
by using either of the commands below. You'll then be able to use the assets from the provided directory.
# Via bower:
$ bower install --save bootstrap.native
# Via NPM:
$ npm install --save bootstrap.native
Additional Styling
Since we are not using jQuery to do all the .slideToggle()
work, and in order to animate things, now we only need to enable the CSS3 transitions. Luckily, we only need one line, for Collapse component, so copy this line in your application CSS files. Also the dismissible Popover feature require some styling for the closing button.
/* enables CSS3 transition for simple collapses, accordion and also navbar in responsive view */
.collapse { transition: height .3s ease-out; /*-webkit-transition: height .3s ease-out*/ }
/* styles the close button for the dismissible popovers */
.popover .close { position: absolute; top: 7px; right: 10px; }
In the above CSS rule for .collapse
class the webkit variant is commented because there seem to be some bug with most Safari versions, messing up Collapse animation. You must test how it works with or without it.
Browser Support
The scripts are tested to work perfect in all major browsers, and legacy browsers starting with IE8. Legacy browsers don't support CSS3 transitions and in order to make legacy browsers behave with the clean and fast code of today's HTML5 standards, make sure you include a polyfill that covers most of the scripts HTML5 code requirements for them. For production websites use:
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
Alternativelly, for Native Javascript for Bootstrap I made a lightweight polyfill with most essential features called minifill, and this can be combined with HTML5 shims on IE8 or generally all IE versions, since most of them don't cover support for the standardized Event
:
<script src="https://cdn.jsdelivr.net/minifill/0.0.3/minifill.min.js"> </script>
<!--[if IE]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<![endif]-->
Generally the scripts rely on very few unsupported features, so starting with 0.9.8 versions, some polyfill dependencies have been removed for better usability and reach. The important polyfills are: indexOf
, getComputedStyle
, Event
(includes addEventListener
, CustomEvent
and dispatchEvent
) and have been packed with minifill. Any of the above choice should do, but apparently legacy browsers perform better with minifill, and the resons why the automated service renders legacy browsers slow is unknown for now.
Remember that the polyfill link(s) must be in your <head>
, especially the HTML5 shims, so that the legacy browsers can render the content properly. As for minifill, you can leave it there for all the browsers; make sure you check this example page here.
Before you go
All scripts run their specific functions right away, including Tooltip and Popover, as long as you use properly their DATA API attributes, so all except Button state/text toggle, you need to bind a handler for that, like the example shown here.
When a script targets an element via it's ID
attribute, we always use getElementById
, for obvious performance reasons. The other cases such as Collapse the target can also be invoked via it's className
and querySelector
is used. Also Collapse features a getClosest
function that works this way, and this function requires valid HTML, also make sure to include the shims.
Some functions have been dropped since I personally never found any use of them, but stay calm, each script example below will provide enough you need for the web but also will provide detailed info on what's changed.
Scripts doing transitions don't make use of any functions to detect transitionend
, for performance and other reasons, we all know a fade is 150ms or carousel performs a 600ms slide animation, and most scripts have a simple option for that.
Don't use Modernizr or respond.js, they both make legacy browsers unusable. To target specific browsers, there are plenty of options. Also, the best way to target the Microsoft's legacy browsers IE9- is by using their proprietary synthax. All this is to avoid errors or not emulate transitionend
when not supported. While you could do something like adding via Javascript the ie ie[version]
class to your html tag:
<!--[if IE 8]><html class="ie ie8" lang="en"><![endif]-->
or simply
<!--[if lt IE 10]><html class="ie" lang="en"><![endif]-->
starting with version 1.0.0 this is no longer a requirement, but a note for you to learn about the best practices. If you care to dig even deeper into this practice, here's a full reference on that.
About that respond.js thing, here is a 2k file of CSS to make your site's layout look normal on IE8. Why? Because CSS is still faster and better in most cases, while the Javascript will heavily handle the browser's resize event, making it unresponsive and unusable.
Examples
Modal
Modal is a great script for displaying special contents in popups, either by using static content or dynamic content with the help from the template system. Check the examples below and the additional notes for more information.
Options
- content - the modal script comes with a template system instead of a load remote content function (Bootstrap 4 drops it). This option is only for Javascript invocation.
- duration - if you are customizing the fade animation duration for Modal, you need to provide a duration via Javascript invoke function or
data-duration="DURATION"
attribute, an option to make sure everything is syncronized. This option is300
by default, just like Bootstrap Modal fade duration. - keyboard - option to dismiss the current modal via Esc key. This option is
true
by default. - backdrop - option use / not the backdrop. This option is
true
by default.
Examples
Now let's have a look at some examples and write some more instructions.
The first example above is just about the exact same as the first example at Bootstrap demo page, everything is exactly the same. The next two examples use the Modal template system. Here's how to do:
<!-- first, you need to provide a basic modal structure -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
The backdrop will be added automatically if not otherwise disabled. Ok now we need a trigger.
<!-- the modal can be triggered via a button with data-target="#myModal" attribute (example 2) -->
<button id="custom-modal-template" type="button" data-toggle="modal" class="btn btn-default btn-lg" data-target="#myModal">Launch modal from template</button>
<!-- or a link with href="#myModal" attribute (example 3) -->
<a id="custom-modal-template" data-toggle="modal" class="btn btn-default btn-lg" href="#myModal">Launch modal from template</a>
Finally we need a proper handler function to use the template system and fill the <div class="modal-content">
element. The example below can be found in the ../assets/js/scripts.js
file.
// we need a blank modal to fill up
var modalFrame = document.getElementById('myModal');
// we grab the button trigger by it's ID
var btnModal = document.getElementById('custom-modal-template');
btnModal.addEventListener('click', function() {
//template content for modal example 2, should work for the third button as well
var modal2 = new Modal(modalFrame, {
content:
'<div class="modal-header">'
+'<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'
+'<h4 class="modal-title" id="gridModalLabel">Modal title</h4>'
+'</div>'
+'<div class="modal-body">'
+'<p>This is where you fill up content you know, etc.</p>'
+'</div>'
+'<div class="modal-footer">'
+'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
+'<button type="button" class="btn btn-primary">Save changes</button>'
+'</div>'});
});
By changing the innerHTML
of the modal-header
, modal-body
or modal-footer
with variables, you can achieve exactly the same as the other examples from the demo of the original plugin.
Additional Note
Modal has no events attached, such as show.bs.modal
or shown.bs.modal
, but if devs would need them, you can have a look at the code of carousel, it implements the events just like the original plugin.
Modal also has no method as described in the documentation of the original script, except the options.
Dropdown
Dropdown opens the dropdown-menu on click and closes it on click/blur after a 200ms timeout, to allow the click event on it's menu items, including external links. Dropdown doesn't cover the original methods or events, but will properly handle all events, especially blur
, even for later added dropdown elements.
Above all, the script will also allow users to dismiss the dropdown by pressing the Esc button.
Scrollspy
ScrollSpy requires the element and all it's childNodes
to have position: relative
and fill the entire area, so it does not work on targeting headings. See the notes below the example.
The script does not cover the original methods, events or option, can only be controlled via DATA API.
.nav
component, where the original plugin targets it's wrapper, and this was creating lots of confusion.
Options
- target - the only option for Scrollspy, is the target of the container with
data-spy="scroll"
attribute. Can be set as shown via DATA API or Javascript. See notes for the example below.
Example
@fat
Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.
@mdo
Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.
one
Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.
two
In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.
three
Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.
Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.
The above example, is the exact same as for the original plugin. For this example we are having the scrollTarget
as the element itself and above it the .nav
component to target the Scrollspy object.
<!-- this is our element -->
<div data-spy="scroll" data-target="#navbar-example2" class="scrollspy-example">
<!-- this is our element's target, the nav component -->
<ul id="navbar-example2" class="nav">
Generally for Scrollspy to work perfect, you would want to avoid incorrect behavior because the element's children don't fill their entire area, you may consider using:
.scrollspy-example > * { float: left; width: 100%; clear: both }
Also like the original plugin, the other example in this page is the side navigation on the right side that pins to top. This example uses the window
as the internal scrollTarget
, but you don't have to worry about that, it's just for you to know.
Tab
Tab works with any kind of navigation components in Bootstrap as you can see in the example below. The script only works via DATA API, and has no support for the original methods or events. Unlike the original plugin, the animation is smooth because it waits for the current active tab to fade away first before animating the next.
Options
- duration - the only option for Tab, is an internal 150ms duration setting to emulate
transitionend
. If you are using a different fade duration than the default plugin, this can be set viadata-duration="DURATION"
attribute.
Example
Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.
Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.
Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.
Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.
Tooltip
This here is an example Tooltip only using data-toggle="tooltip"
. Unlike the original Bootstrap Tooltip, the native Javascript version here can do automatic placement, without any additional options required. Another key difference is that this script will never bubble, also worth mentioning it works perfect with IE8+ and is half the size of the original script.
Now let's test all the other placement positions, we start with the bottom placement, then left, and right.
Options
- animation - option to customize the Tooltip animation. If you are using a different animation other than
fade
, you can specify that viadata-animation="ANIMATION"
attribute. This will add an additional CSS class to the Tooltip to enable a custom transition. The default value isfade
. - placement - option to set a specific Tooltip placement to
top
,bottom
,left
orright
, relative to it's target. The default value istop
. - duration - is an internal 150ms duration setting to emulate
transitionend
. If you are using a different duration than the default plugin, this can be set viadata-duration="DURATION"
attribute. The default value is150
. - delay - is an internal 100ms delay before generating the tooltip, helpful for legacy browsers to be able to compute the automatic positioning. Can be set via
data-delay="DELAY"
attribute. The default value is100
.
Examples
Let's put it to the test! Some heavy testing on the automatic repositioning with very very long tooltips.
Additional Note
You can also enable Tooltip for elements not having the specific DATA API, but have a title="Not null title"
attribute. You can do the following:
// find all elements with title attribute
var elementsTooltip = document.querySelectorAll('[title]');
// attach a tooltip for each
for (var i = 0; i < elementsTooltip.length; i++){
new Tooltip(elementsTooltip[i], {
placement: 'top', //string
animation: 'slideNfade', // CSS class
duration: 200, // integer
delay: 150, // integer
})
}
Tooltip always uses the document.body
as the containe and doesn't cover template system like the original, and remember that it can do automatic placement without any additional options.
Popover
This here is an example Popover using data-toggle="popover"
. Unlike the original Bootstrap Popover, this script does not require the Tooltip script and works just about the same as the above except that Popover has, like the original script, the ability to work with templates and trigger options: hover
(default), click
and focus
.
Without further talking, let's test all the options, and placement positions, we start with the bottom placement, then left, and right.
Options
- template - via Javascript, you can dynamically create popovers via the template system. See examples below.
- content - the
data-content="CONTENT"
attribute to fill the Popover. If the template is not specified via Javascript or the content option is not set, the Popover will not initiate. - title - the
data-title="TITLE"
attribute to fill the Popover title. - trigger - option to change the Popover trigger event:
hover
,focus
andclick
. In some cases you may want to open Popover onfocus
for form elements orclick
for other buttons, you can specify that viadata-trigger="EVENT"
attribute. The default value ishover
. - animation - option to customize the Popover animation. If you are using a different animation other than
fade
, you can specify that viadata-animation="ANIMATION"
attribute. This will add an additional CSS class to the Popover to enable a custom transition. The default value isfade
. - dismiss - option to make the Popover dismissible. When used, it will also add an X button at the top-right of the popover. You can enable this option via
data-dismiss="true"
attribute. The default value isfalse
. - placement - option to set a specific Popover placement to
top
,bottom
,left
orright
, relative to it's target. The default value istop
. - duration - is an internal 150ms duration setting to emulate
transitionend
. If you are using a different duration than the default plugin, this can be set viadata-duration="DURATION"
attribute. The default value is150
. - delay - is an internal 100ms delay before generating the Popover, helpful for legacy browsers to be able to compute the automatic positioning. Can be set via
data-delay="DELAY"
attribute. The default value is100
.
Examples
Now we are going to test buttons and Popover with large contents. The last two examples below are using the template system and different trigger options. The Popover generated for the last two examples can be dismissed on window resize or blur (focus out).
Additional Note
To use the template system, you can attach a custom handler to a target as the following:
//define some variables or get their values from other scripts
var someTitleFromOtherCode = 'Sample title';
var someContentFromOuterSpace = '<p>Some sample message.</p>';
//initiate Popover with the template
var popover2 = new Popover('.popover-via-template', { // where .popover-via-template is the text input
trigger: 'focus',
template: '<div class="popover" role="tooltip">'
+ '<div class="arrow"></div>'
+ '<h3 class="popover-title">'+someTitleFromOtherCode+'</h3>'
+ '<div class="popover-content">'+someContentFromOuterSpace+'</div>'
+ '</div>'
});
The above code can be found in the ../assets/js/scripts.js
file.
Remember - Popover always uses the document.body
as the container, and does automatic placement without options.
Alert
Alert does not have any events and methods, it's action simply dismisses the Alert component. This script can successfully handle later added alerts into the DOM. See Button first example below.
Oh snap! You got an error!
Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.
Alert also uses a 150ms internal duration
to emulate transitionend
. No option required or needed really.
Button
Button script allows you to change the text of a given button. If using a data-loading-text="Loading.."
attribute, the button will also change it's state to disabled. The other function of the script is to toggle checkboxes and radio buttons, it's a most awaited form replacement for the good old checks and radios.
Options
- STRING-text - the only option for Button, allows you to change a button's text via it's
data-OPTION-text="Sample text"
attribute.
Example
This is a quick example of button setting state via string options. Like the original script we make an example for loading
state for the button. For the purpose of testing here, the button will come back to original state after a short setTimeout
delay.
Basic Usage
<!-- this is the example button -->
<button type="button" id="myButton" data-toggle="button" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">
Loading state
</button>
//the method works like this
var btn = document.getElementById('myButton');
btn.addEventListener('click', function() {
new Button(btn,'loading'); //this assumes button has a data-loading-text="Loading..." attribute
});
This action will create an additional data-original-title="Loading state"
attribute, required for the below reset
method.
//the reset method works like this
new Button(btn,'reset');
Next we will toggle some checkboxes. You should open your console to test the handler functions bound by the change
event of the following checkboxes and radio buttons.
Finally we toggle radio buttons.
As a quick note, here's the example for checkboxes.
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
</label>
<label class="btn btn-default">
<input type="checkbox" autocomplete="off"> Checkbox 2
</label>
<label class="btn btn-default">
<input type="checkbox" autocomplete="off"> Checkbox 3
</label>
</div>
The ../assets/js/scripts.js
file has some console log functions bound by the change of the .btn-group
components. When using polyfills and since the change
event isn't fired properly on legacy browsers, you can make use of the custom bs.button.change
event to bind into context other functions. Example:
//let's do some custom binding action
myCheckBoxesGroup.addEventListener('bs.button.change', function() {
// do something when anything inside the btn-group changes
});
myRadioInput.addEventListener('bs.button.change',function() {
// do something only when this specific input changes
});
Additional Notes
Button will activate automatically for all .btn-group
component instances if they have data-toggle="buttons"
and the appropriate input elements inside like our examples here.
The script properly covers the "change" event for checkbox and radio buttons, but via a custom event called bs.button.change
, allowing other functions to bind into context. The event is also bound to the .btn-group
component, but to use it, you have to use polyfills for legacy browsers.
The script doesn't have any method to control it's toggle functions for checkbox and radio buttons as described by the documentation of the original plugin. Button also doesn't cover single toggle.
Collapse
Collapse is a great way to toggle content, and it's also used for collapsible navbar. It's not animating on modern browsers unless you use the provided CSS, and legacy browsers don't support transitions. Unlike other scripts, this is the only component that can be targeted by it's toggle links by it's className
via the data-target="className"
attribute, along with the traditional data-target="#collapse-id"
. The collapsible navbar in Bootstrap for instance works mostly via data-target=".bs-navbar-collapse"
attribute.
Collapse requires proper wrapping of contents, similar to wells, accordion and responsive navbar examples. With other words, you cannot toggle a bunch of paragraphs at once unless you wrap them into a container and give it a unique ID and a collapse
class.
Options
- duration - the only option required is a 300ms duration internal setting just as in the provided CSS, to emulate
transitionend
for modern browsers. If you use a different duration, you can specify that viadata-duration="DURATION"
attribute.
Examples
Here's a quick collapse demonstration, but I would also recommend you to try the navbar on this page on a smaller screen size or on a mobile device.
Here's an Accordion component, basically a set of Panel components. When the toggle links are clicked, our Collapse object will look for the closest <div class="accordion-className"
or <div id="accordion-id"
via data-parent="selector"
.
Remember that all toggle links must reference the accordion via data-parent="selector"
as described above in order to collapse current opened container.
Carousel
Carousel is an excelent content showcase script, and as the original plugin, it handles both slid
and slide
events, just as shown in the example below.
The script uses an internal duration value (default Bootstrap Carousel transition duration) + 100ms more, needed to emulate transitionend
, and during this time, all click handlers are disabled to prevent any animation issue or code bubbles, similar to the original script. On legacy browsers this duration is 100ms and your HTML tag needs a class ie
for that.
When configured to pause on hover, it also adds a paused
class to it to help prevent any anomalies. The script does not implement the original methods.
Options
- duration - an option to customize the
600ms
internal duration required to emulatetransitionend
for modern browsers. If you use a different duration, you can specify that viadata-duration="DURATION"
attribute. The default value is600
. - interval - the time delay between transitions. If you want to use a different interval, you can specify that via
data-interval="INTERVAL"
attribute. To disable automatic transition, simply usedata-interval="false"
attribute. The default value is5000
. - pause - makes possible to pause the carousel transition on mouse hover and touchdown. If you want to disable pause on hover, do that via
data-pause="false"
attribute. The default value ishover
. - keyboard - enables the carousel to be controllable via left and right keyboard keys. If you want to enable this option, do that via
data-keyboard="true"
attribute. The default value isfalse
.
Example
This is a test demonstrating the carousel capabilities and it's events, so open your console, and start clicking, you will be noticed before and after the animation.
The handlers bound to Carousel's specific events explain what happens with the other example in this site's header. Let's have a quick look at it.
//demo myCarousel demonstrating the slid and slide events
var mainSlider = document.getElementById('myCarousel');
mainSlider.addEventListener('slid.bs.carousel', function(e) {
// get the caption of current active item before slide
var active = mainSlider.querySelector('.item.active .carousel-caption');
active.classList.remove('slide')
});
mainSlider.addEventListener('slide.bs.carousel', function(e) {
// get the caption of new active item after slide
var active = mainSlider.querySelector('.item.active .carousel-caption');
active.classList.add('slide')
});
Additional Notes
Carousel does not use DATA API for previous and next navigation controls, which means you can ignore data-slide="prev"
and data-slide="next"
attributes, but they must have at least class="carousel-control"
.
The script properly covers both the original custom events slid.bs.carousel
and slide.bs.carousel
, allowing other functions to bind into context. To use it, you have to use polyfills for legacy browsers.
Affix
Affix is the one little script pinning the side navigation to top once the scroll reaches a certain offset value. It works exactly like the original and requires some additional CSS in order to work properly. When scrolling the page, the given element will receive an affix
class once the scroll reaches the target or given offset value, and further more an additional affix-bottom
class once the scroll value reaches the maximum scroll height at the given bottom offset.
Options
- target - Affix can pin an element to top once the scroll reaches it's target offsetTop. You can set the target via
data-target="target-className"
ordata-target="#target-ID"
attribute. - offsetTop - allows an element to pin to top when scroll reaches a specific value. This can be set via
data-offset-top="OFFSET"
attribute, where OFFSET is integer. Via Javascript you can also assign a function to ouroffsetTop
option. - offsetBottom - allows an element to pin to bottom at a certain offset relative to the window maximum scroll. This can be set via
data-offset-bottom="OFFSET"
attribute, where OFFSET is integer. Via Javascript you can also assign a function to ouroffsetBottom
option.
Example
Here we go, we'll have a look at our example here and explain things. First we configure an element to be pinned to top and / or bottom.
<ul class="nav nav-stacked" data-spy="affix" data-target="#use" data-offset-bottom="200">
Alternatively, via Javascript we can achieve the same with:
//grab the element by it's ID
var elToAffix = document.getElementById('myNav');
var theAffix = new Affix(elToAffix, {
target: '#use',
offsetBottom: 200,
});
Similar to the original plugin, we can make use of a function, we can determine the offsetTop value from the height of the previous element above the initial target:
var elToAffix = document.getElementById('myNav');
var theAffix = new Affix(elToAffix, {
offsetTop: function(){
return document.getElementById('myCarousel').offsetHeight
},
offsetBottom: 200,
});
Now we must make sure our element is properly styled to make sure it works properly.
/* this style applies to mobile devices, on screens SMALLER than 768px */
/* affix example */
#side-nav {clear: both}
#side-nav .nav.affix,
#side-nav .nav.affix.affix-bottom { position: relative; margin: 20px 0; }
/* this style applies to other devices, on screens LARGER than 768px */
@media (min-width: 768px) {
/* affix example */
#side-nav .nav.affix { position: fixed !important; width: 263px; top: 0; }
#side-nav .nav.affix.affix-bottom { top: auto; bottom: 150px; }
}
Additional Note
Using static values for offsetTop
and / or offsetBottom
would work best on non-responsive websites, or when the elements don't change their height when window resize occurs.
The given ../assets/js/script.js
also provides a way to automatically resize the pinned element when window resize occurs. Make sure you check that too.
About
Why Native Javascript?
Mission | The Native Javascript for Bootstrap project was born to help. It doesn't totally and perfectly replace all the functions the jQuery Plugins have for Bootstrap, but the essential tools. In many cases it performs much better than the original code, like an upgraded version of the original. I've literally learned to code native Javascript developing these scripts here. To sum up, this aims to help me and you transition into a better developer, doing things right from the next big project.
Context | Today's most popular HTML5 framework is Bootstrap and like any other there's ups and downs. We all know about the PROs, but one of the CONs is the jQuery dependency. Why in the world would you ever drop jQuery? What can you put in it's place? The answer is this this: clean Javascript code. All browsers on all devices support it or they damn should be, because nothing would work, not even jQuery, Zepto, Dojo, AngularJS, whatever. The latest trends indicate that jQuery already peaked and is becoming less and less relevant.
Perspective | The standards are now generally adopted and mobile platforms are "on the wave". The future brings more changes and we cannot fix-n-hack or hack-to-fix anymore via jQuery. Performance is the one and only true goal to follow, so if dropping jQuery and cleaning up the code is the way to go, we'll go for it. jQuery is still so cool and efficient but I feel it's too overpowered with it's cross-browser solutions. With the new Javascript engines and HTML5 standards, really, why not code native code, it's really not that hard.
Really Write Less, Do More?
Why do I feel this sounds much too bold after only a few weeks of vanilla Javascript? With the given Javascript here and some CSS customizations you can now do alot more than jQuery with the original Bootstrap plugins. As I have shown here, I think I've completely blasted the "do more" myth.
If you forgot to check performance metrics, go ahead (there are lots more out there, plus a ton of guides on how to boost performance), there is also the page load speed issue I forgot to mention. Imagine you can be drastically improve the page load by dropping jQuery.
If we compare the size of jQuery v1.11.2 + Bootstrap v3.3.5 minified is just about 93Kb + 36Kb = 129Kb. Our scripts here are (depending on your browser) 18Kb + 36Kb = between 38Kb and 54Kb, where 18Kb is the maximum size of the minified polyfill for IE8, mostly under 5kb for most modern browsers.
This being said, jQuery doesn't make any sense for many of us.