Sie sind auf Seite 1von 51

7/5/2016

JavaScript Bootstrap

Awwyeah,Bootstrap4iscoming!(http://blog.getbootstrap.com/2015/08/19/bootstrap4alpha/)

JavaScript
BringBootstrap'scomponentstolifewithoveradozencustomjQuery
plugins.Easilyincludethemall,oronebyone.

(http://www.launchbit.com/taz/95336408111/)
MonitorandIdentify,24x7,
sloworfailingproduction
JavaMethod,using
Germain
(http://www.launchbit.com/taz/9533
6408111/)
adsviaCarbon
(http://carbonads.net/)

Overview
Individualorcompiled
Pluginscanbeincludedindividually(usingBootstrap'sindividual *.jsfiles),orallatonce(using
bootstrap.jsortheminified bootstrap.min.js).

UsingthecompiledJavaScript
Both bootstrap.jsand bootstrap.min.jscontainallpluginsinasinglefile.Includeonly
one.

Plugindependencies
http://getbootstrap.com/javascript/

1/51

7/5/2016

JavaScript Bootstrap

SomepluginsandCSScomponentsdependonotherplugins.Ifyouincludepluginsindividually,
makesuretocheckforthesedependenciesinthedocs.Alsonotethatallpluginsdependon
jQuery(thismeansjQuerymustbeincludedbeforethepluginfiles).Consultour bower.json
(https://github.com/twbs/bootstrap/blob/v3.3.6/bower.json)toseewhichversionsofjQueryare
supported.

Dataattributes
YoucanuseallBootstrappluginspurelythroughthemarkupAPIwithoutwritingasinglelineof
JavaScript.ThisisBootstrap'sfirstclassAPIandshouldbeyourfirstconsiderationwhenusinga
plugin.
Thatsaid,insomesituationsitmaybedesirabletoturnthisfunctionalityoff.Therefore,wealsoprovide
theabilitytodisablethedataattributeAPIbyunbindingalleventsonthedocumentnamespacedwith
dataapi.Thislookslikethis:
$(document).off('.dataapi')

Alternatively,totargetaspecificplugin,justincludetheplugin'snameasanamespacealongwiththe
dataapinamespacelikethis:
$(document).off('.alert.dataapi')

Onlyonepluginperelementviadataattributes
Don'tusedataattributesfrommultiplepluginsonthesameelement.Forexample,abutton
cannotbothhaveatooltipandtoggleamodal.Toaccomplishthis,useawrappingelement.

ProgrammaticAPI
WealsobelieveyoushouldbeabletouseallBootstrappluginspurelythroughtheJavaScriptAPI.All
publicAPIsaresingle,chainablemethods,andreturnthecollectionactedupon.
$('.btn.danger').button('toggle').addClass('fat')

Allmethodsshouldacceptanoptionaloptionsobject,astringwhichtargetsaparticularmethod,or
nothing(whichinitiatesapluginwithdefaultbehavior):
$('#myModal').modal()//initializedwithdefaults
$('#myModal').modal({keyboard:false})//initializedwithno
keyboard
$('#myModal').modal('show')//initializesandinvokes
showimmediately

http://getbootstrap.com/javascript/

2/51

7/5/2016

JavaScript Bootstrap

Eachpluginalsoexposesitsrawconstructorona Constructorproperty:
$.fn.popover.Constructor.Ifyou'dliketogetaparticularplugininstance,retrieveitdirectlyfroman
element: $('[rel="popover"]').data('popover').

Defaultsettings
Youcanchangethedefaultsettingsforapluginbymodifyingtheplugin's Constructor.DEFAULTS
object:
$.fn.modal.Constructor.DEFAULTS.keyboard=false//changesdefaultfor
themodalplugin's`keyboard`optiontofalse

Noconflict
SometimesitisnecessarytouseBootstrappluginswithotherUIframeworks.Inthesecircumstances,
namespacecollisionscanoccasionallyoccur.Ifthishappens,youmaycall .noConflictontheplugin
youwishtorevertthevalueof.
varbootstrapButton=$.fn.button.noConflict()//return$.fn.buttonto
previouslyassignedvalue
$.fn.bootstrapBtn=bootstrapButton//give$().bootstrapBtn
theBootstrapfunctionality

Events
Bootstrapprovidescustomeventsformostplugins'uniqueactions.Generally,thesecomeinan
infinitiveandpastparticipleformwheretheinfinitive(ex. show)istriggeredatthestartofanevent,
anditspastparticipleform(ex. shown)istriggeredonthecompletionofanaction.
Asof3.0.0,allBootstrapeventsarenamespaced.
Allinfinitiveeventsprovide preventDefaultfunctionality.Thisprovidestheabilitytostopthe
executionofanactionbeforeitstarts.
$('#myModal').on('show.bs.modal',function(e){
if(!data)returne.preventDefault()//stopsmodalfrombeingshown
})

Versionnumbers
TheversionofeachofBootstrap'sjQuerypluginscanbeaccessedviathe VERSIONpropertyofthe
plugin'sconstructor.Forexample,forthetooltipplugin:
$.fn.tooltip.Constructor.VERSION//=>"3.3.6"

NospecialfallbackswhenJavaScriptis
disabled
http://getbootstrap.com/javascript/

3/51

7/5/2016

JavaScript Bootstrap

Bootstrap'spluginsdon'tfallbackparticularlygracefullywhenJavaScriptisdisabled.Ifyoucareabout
theuserexperienceinthiscase,use <noscript>(https://developer.mozilla.org/en
US/docs/Web/HTML/Element/noscript)toexplainthesituation(andhowtoreenableJavaScript)to
yourusers,and/oraddyourowncustomfallbacks.

Thirdpartylibraries
BootstrapdoesnotofficiallysupportthirdpartyJavaScriptlibrarieslikePrototypeor
jQueryUI.Despite .noConflictandnamespacedevents,theremaybecompatibility
problemsthatyouneedtofixonyourown.

Transitionstransition.js
Abouttransitions
Forsimpletransitioneffects,include transition.jsoncealongsidetheotherJSfiles.Ifyou'reusing
thecompiled(orminified) bootstrap.js,thereisnoneedtoincludethisit'salreadythere.

What'sinside
Transition.jsisabasichelperfor transitionEndeventsaswellasaCSStransitionemulator.It'sused
bytheotherpluginstocheckforCSStransitionsupportandtocatchhangingtransitions.

Disablingtransitions
TransitionscanbegloballydisabledusingthefollowingJavaScriptsnippet,whichmustcomeafter
transition.js(or bootstrap.jsor bootstrap.min.js,asthecasemaybe)hasloaded:
$.support.transition=false

Modalsmodal.js
Modalsarestreamlined,butflexible,dialogpromptswiththeminimumrequiredfunctionalityandsmart
defaults.

Multipleopenmodalsnotsupported
http://getbootstrap.com/javascript/

4/51

7/5/2016

JavaScript Bootstrap

Besurenottoopenamodalwhileanotherisstillvisible.Showingmorethanonemodalata
timerequirescustomcode.

Modalmarkupplacement
Alwaystrytoplaceamodal'sHTMLcodeinatoplevelpositioninyourdocumenttoavoidother
componentsaffectingthemodal'sappearanceand/orfunctionality.

Mobiledevicecaveats
Therearesomecaveatsregardingusingmodalsonmobiledevices.Seeourbrowsersupport
docs(../gettingstarted/#supportfixedpositionkeyboards)fordetails.

DuetohowHTML5definesitssemantics,the autofocusHTMLattributehasnoeffectin
Bootstrapmodals.Toachievethesameeffect,usesomecustomJavaScript:
$('#myModal').on('shown.bs.modal',function(){
$('#myInput').focus()
})

Examples
Staticexample
Arenderedmodalwithheader,body,andsetofactionsinthefooter.
EXAMPLE

Modaltitle
Onefinebody

Close

http://getbootstrap.com/javascript/

Savechanges

5/51

7/5/2016

JavaScript Bootstrap

<divclass="modalfade"tabindex="1"role="dialog">
<divclass="modaldialog">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"aria
label="Close"><spanariahidden="true">&times</span></button>
<h4class="modaltitle">Modaltitle</h4>
</div>
<divclass="modalbody">
<p>Onefinebody&hellip</p>
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"data
dismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Savechanges</button>
</div>
</div><!/.modalcontent>
</div><!/.modaldialog>
</div><!/.modal>

Livedemo
ToggleamodalviaJavaScriptbyclickingthebuttonbelow.Itwillslidedownandfadeinfromthetopof
thepage.
EXAMPLE

Launchdemomodal

http://getbootstrap.com/javascript/

6/51

7/5/2016

JavaScript Bootstrap

<!Buttontriggermodal>
<buttontype="button"class="btnbtnprimarybtnlg"datatoggle="modal"
datatarget="#myModal">
Launchdemomodal
</button>
<!Modal>
<divclass="modalfade"id="myModal"tabindex="1"role="dialog"aria
labelledby="myModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"aria
label="Close"><spanariahidden="true">&times</span></button>
<h4class="modaltitle"id="myModalLabel">Modaltitle</h4>
</div>
<divclass="modalbody">
...
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"data
dismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Savechanges</button>
</div>
</div>
</div>
</div>

Makemodalsaccessible
Besuretoadd role="dialog"and arialabelledby="...",referencingthemodaltitle,to
.modal,and role="document"tothe .modaldialogitself.

Additionally,youmaygiveadescriptionofyourmodaldialogwith ariadescribedbyon
.modal.

EmbeddingYouTubevideos
EmbeddingYouTubevideosinmodalsrequiresadditionalJavaScriptnotinBootstrapto
automaticallystopplaybackandmore.SeethishelpfulStackOverflowpost
(https://stackoverflow.com/questions/18622508/bootstrap3andyoutubeinmodal)formore
information.

Optionalsizes
Modalshavetwooptionalsizes,availableviamodifierclassestobeplacedona .modaldialog.

http://getbootstrap.com/javascript/

7/51

7/5/2016

JavaScript Bootstrap

EXAMPLE

Largemodal Smallmodal

<!Largemodal>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"data
target=".bsexamplemodallg">Largemodal</button>
<divclass="modalfadebsexamplemodallg"tabindex="1"role="dialog"
arialabelledby="myLargeModalLabel">
<divclass="modaldialogmodallg">
<divclass="modalcontent">
...
</div>
</div>
</div>
<!Smallmodal>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"data
target=".bsexamplemodalsm">Smallmodal</button>
<divclass="modalfadebsexamplemodalsm"tabindex="1"role="dialog"
arialabelledby="mySmallModalLabel">
<divclass="modaldialogmodalsm">
<divclass="modalcontent">
...
</div>
</div>
</div>

Removeanimation
Formodalsthatsimplyappearratherthanfadeintoview,removethe .fadeclassfromyourmodal
markup.
<divclass="modal"tabindex="1"role="dialog"arialabelledby="...">
...
</div>

Usingthegridsystem
TotakeadvantageoftheBootstrapgridsystemwithinamodal,justnest .rowswithinthe .modal
bodyandthenusethenormalgridsystemclasses.
EXAMPLE

Launchdemomodal
http://getbootstrap.com/javascript/

8/51

7/5/2016

JavaScript Bootstrap

<divclass="modalfade"tabindex="1"role="dialog"aria
labelledby="gridSystemModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"aria
label="Close"><spanariahidden="true">&times</span></button>
<h4class="modaltitle"id="gridSystemModalLabel">Modaltitle</h4>
</div>
<divclass="modalbody">
<divclass="row">
<divclass="colmd4">.colmd4</div>
<divclass="colmd4colmdoffset4">.colmd4.colmdoffset
4</div>
</div>
<divclass="row">
<divclass="colmd3colmdoffset3">.colmd3.colmdoffset
3</div>
<divclass="colmd2colmdoffset4">.colmd2.colmdoffset
4</div>
</div>
<divclass="row">
<divclass="colmd6colmdoffset3">.colmd6.colmdoffset
3</div>
</div>
<divclass="row">
<divclass="colsm9">
Level1:.colsm9
<divclass="row">
<divclass="colxs8colsm6">
Level2:.colxs8.colsm6
</div>
<divclass="colxs4colsm6">
Level2:.colxs4.colsm6
</div>
</div>
</div>
</div>
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"data
dismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Savechanges</button>
</div>
</div><!/.modalcontent>
</div><!/.modaldialog>
</div><!/.modal>

Varyingmodalcontentbasedontriggerbutton
http://getbootstrap.com/javascript/

9/51

7/5/2016

JavaScript Bootstrap

Haveabunchofbuttonsthatalltriggerthesamemodal,justwithslightlydifferentcontents?Use
event.relatedTargetandHTML data*attributes(https://developer.mozilla.org/en
US/docs/Web/Guide/HTML/Using_data_attributes)(possiblyviajQuery(http://api.jquery.com/data/))to
varythecontentsofthemodaldependingonwhichbuttonwasclicked.SeetheModalEventsdocsfor
detailson relatedTarget,
EXAMPLE

Openmodalfor@mdo Openmodalfor@fat Openmodalfor@getbootstrap ...more


buttons...
<buttontype="button"class="btnbtnprimary"datatoggle="modal"data
target="#exampleModal"datawhatever="@mdo">Openmodalfor@mdo</button>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"data
target="#exampleModal"datawhatever="@fat">Openmodalfor@fat</button>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"data
target="#exampleModal"datawhatever="@getbootstrap">Openmodalfor
@getbootstrap</button>
...morebuttons...
<divclass="modalfade"id="exampleModal"tabindex="1"role="dialog"aria
labelledby="exampleModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"aria
label="Close"><spanariahidden="true">&times</span></button>
<h4class="modaltitle"id="exampleModalLabel">Newmessage</h4>
</div>
<divclass="modalbody">
<form>
<divclass="formgroup">
<labelfor="recipientname"class="controllabel">Recipient:
</label>
<inputtype="text"class="formcontrol"id="recipientname">
</div>
<divclass="formgroup">
<labelfor="messagetext"class="controllabel">Message:</label>
<textareaclass="formcontrol"id="messagetext"></textarea>
</div>
</form>
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"data
dismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Sendmessage</button>
</div>
</div>
</div>
</div>

http://getbootstrap.com/javascript/

10/51

7/5/2016

JavaScript Bootstrap

$('#exampleModal').on('show.bs.modal',function(event){
varbutton=$(event.relatedTarget)//Buttonthattriggeredthemodal
varrecipient=button.data('whatever')//Extractinfofromdata*
attributes
//Ifnecessary,youcouldinitiateanAJAXrequesthere(andthendo
theupdatinginacallback).
//Updatethemodal'scontent.We'llusejQueryhere,butyoucould
useadatabindinglibraryorothermethodsinstead.
varmodal=$(this)
modal.find('.modaltitle').text('Newmessageto'+recipient)
modal.find('.modalbodyinput').val(recipient)
})

Usage
Themodalplugintogglesyourhiddencontentondemand,viadataattributesorJavaScript.Italsoadds
.modalopentothe <body>tooverridedefaultscrollingbehaviorandgeneratesa .modal
backdroptoprovideaclickareafordismissingshownmodalswhenclickingoutsidethemodal.

Viadataattributes
ActivateamodalwithoutwritingJavaScript.Set datatoggle="modal"onacontrollerelement,likea
button,alongwitha datatarget="#foo"or href="#foo"totargetaspecificmodaltotoggle.
<buttontype="button"datatoggle="modal"datatarget="#myModal">Launch
modal</button>

ViaJavaScript
Callamodalwithid myModalwithasinglelineofJavaScript:
$('#myModal').modal(options)

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin databackdrop="".
Name

type

default

description

backdrop

booleanor
thestring

true

Includesamodalbackdropelement.Alternatively,specify
staticforabackdropwhichdoesn'tclosethemodalon
click.

'static'

keyboard

boolean

true

Closesthemodalwhenescapekeyispressed

show

boolean

true

Showsthemodalwheninitialized.

remote

path

false

http://getbootstrap.com/javascript/

11/51

7/5/2016

JavaScript Bootstrap

Thisoptionisdeprecatedsincev3.3.0andhasbeen
removedinv4.Werecommendinsteadusingclientside
templatingoradatabindingframework,orcalling
jQuery.load(http://api.jquery.com/load/)yourself.
IfaremoteURLisprovided,contentwillbeloadedone
timeviajQuery's loadmethodandinjectedintothe
.modalcontentdiv.Ifyou'reusingthedataapi,you

mayalternativelyusethe hrefattributetospecifythe
remotesource.Anexampleofthisisshownbelow:
<adatatoggle="modal"
href="remote.html"data
target="#modal">Clickme</a>

Methods
.modal(options)
Activatesyourcontentasamodal.Acceptsanoptionaloptions object.
$('#myModal').modal({
keyboard:false
})

.modal('toggle')
Manuallytogglesamodal.Returnstothecallerbeforethemodalhasactuallybeenshownor
hidden(i.e.beforethe shown.bs.modalor hidden.bs.modaleventoccurs).
$('#myModal').modal('toggle')

.modal('show')
Manuallyopensamodal.Returnstothecallerbeforethemodalhasactuallybeenshown(i.e.
beforethe shown.bs.modaleventoccurs).
$('#myModal').modal('show')

.modal('hide')
Manuallyhidesamodal.Returnstothecallerbeforethemodalhasactuallybeenhidden(i.e.
beforethe hidden.bs.modaleventoccurs).
$('#myModal').modal('hide')

.modal('handleUpdate')

http://getbootstrap.com/javascript/

12/51

7/5/2016

JavaScript Bootstrap

Readjuststhemodal'spositioningtocounterascrollbarincaseoneshouldappear,whichwouldmake
themodaljumptotheleft.
Onlyneededwhentheheightofthemodalchangeswhileitisopen.
$('#myModal').modal('handleUpdate')

Events
Bootstrap'smodalclassexposesafeweventsforhookingintomodalfunctionality.
Allmodaleventsarefiredatthemodalitself(i.e.atthe <divclass="modal">).
EventType

Description

show.bs.modal

Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.If
causedbyaclick,theclickedelementisavailableasthe relatedTarget
propertyoftheevent.

shown.bs.modal

Thiseventisfiredwhenthemodalhasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).Ifcausedbyaclick,theclicked
elementisavailableasthe relatedTargetpropertyoftheevent.

hide.bs.modal

Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.

hidden.bs.modal

Thiseventisfiredwhenthemodalhasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).

loaded.bs.modal

Thiseventisfiredwhenthemodalhasloadedcontentusingthe remote
option.

$('#myModal').on('hidden.bs.modal',function(e){
//dosomething...
})

Dropdownsdropdown.js
Examples
Adddropdownmenustonearlyanythingwiththissimpleplugin,includingthenavbar,tabs,andpills.

Withinanavbar
http://getbootstrap.com/javascript/

13/51

7/5/2016

JavaScript Bootstrap

EXAMPLE

Withinpills
EXAMPLE

Regularlink

Dropdown

Dropdown

Dropdown

Usage
ViadataattributesorJavaScript,thedropdownplugintoggleshiddencontent(dropdownmenus)by
togglingthe .openclassontheparentlistitem.
Onmobiledevices,openingadropdownaddsa .dropdownbackdropasatapareaforclosing
dropdownmenuswhentappingoutsidethemenu,arequirementforproperiOSsupport.Thismeans
thatswitchingfromanopendropdownmenutoadifferentdropdownmenurequiresanextratap
onmobile.
Note:The datatoggle="dropdown"attributeisreliedonforclosingdropdownmenusatan
applicationlevel,soit'sagoodideatoalwaysuseit.

Viadataattributes
Add datatoggle="dropdown"toalinkorbuttontotoggleadropdown.
<divclass="dropdown">
<buttonid="dLabel"type="button"datatoggle="dropdown"aria
haspopup="true"ariaexpanded="false">
Dropdowntrigger
<spanclass="caret"></span>
</button>
<ulclass="dropdownmenu"arialabelledby="dLabel">
...
</ul>
</div>

TokeepURLsintactwithlinkbuttons,usethe datatargetattributeinsteadof href="#".

http://getbootstrap.com/javascript/

14/51

7/5/2016

JavaScript Bootstrap

<divclass="dropdown">
<aid="dLabel"datatarget="#"href="http://example.com"data
toggle="dropdown"role="button"ariahaspopup="true"aria
expanded="false">
Dropdowntrigger
<spanclass="caret"></span>
</a>
<ulclass="dropdownmenu"arialabelledby="dLabel">
...
</ul>
</div>

ViaJavaScript
CallthedropdownsviaJavaScript:
$('.dropdowntoggle').dropdown()

datatoggle="dropdown"stillrequired
RegardlessofwhetheryoucallyourdropdownviaJavaScriptorinsteadusethedataapi,
datatoggle="dropdown"isalwaysrequiredtobepresentonthedropdown'striggerelement.

Options
None

Methods
$().dropdown('toggle')
Togglesthedropdownmenuofagivennavbarortabbednavigation.

Events
Alldropdowneventsarefiredatthe .dropdownmenu'sparentelement.
Alldropdowneventshavea relatedTargetproperty,whosevalueisthetogglinganchorelement.
EventType

Description

show.bs.dropdown

Thiseventfiresimmediatelywhentheshowinstancemethodiscalled.

shown.bs.dropdown

Thiseventisfiredwhenthedropdownhasbeenmadevisibletotheuser
(willwaitforCSStransitions,tocomplete).

hide.bs.dropdown

Thiseventisfiredimmediatelywhenthehideinstancemethodhasbeen
called.

http://getbootstrap.com/javascript/

15/51

7/5/2016

hidden.bs.dropdown

JavaScript Bootstrap

Thiseventisfiredwhenthedropdownhasfinishedbeinghiddenfromthe
user(willwaitforCSStransitions,tocomplete).

$('#myDropdown').on('show.bs.dropdown',function(){
//dosomething
})

ScrollSpyscrollspy.js
Exampleinnavbar
TheScrollSpypluginisforautomaticallyupdatingnavtargetsbasedonscrollposition.Scrollthearea
belowthenavbarandwatchtheactiveclasschange.Thedropdownsubitemswillbehighlightedas
well.
EXAMPLE

@fat
Adleggingskeytar,brunchidartpartydolorlabore.Pitchforkyrenimlofibeforetheysoldoutqui.
Tumblrfarmtotablebicyclerightswhatever.Animkeffiyehcarlescardigan.Velitseitanmcsweeney's
photobooth3wolfmoonirure.Cosbysweaterlomojeanshorts,williamsburghoodieminimquiyou
probablyhaven'theardofthemetcardigantrustfundculpabiodieselwesandersonaesthetic.Nihil
tattooedaccusamus,credironybiodieselkeffiyehartisanullamcoconsequat.

@mdo
Veniammarfamustacheskateboard,adipisicingfugiatvelitpitchforkbeard.Freeganbeardaliqua

Usage
RequiresBootstrapnav
ScrollspycurrentlyrequirestheuseofaBootstrapnavcomponent(../components/#nav)for
properhighlightingofactivelinks.

ResolvableIDtargetsrequired
Navbarlinksmusthaveresolvableidtargets.Forexample,a <ahref="#home">home</a>
mustcorrespondtosomethingintheDOMlike <divid="home"></div>.
http://getbootstrap.com/javascript/

16/51

7/5/2016

JavaScript Bootstrap

Non :visibletargetelementsignored
Targetelementsthatarenot :visibleaccordingtojQuery(http://api.jquery.com/visible
selector/)willbeignoredandtheircorrespondingnavitemswillneverbehighlighted.

Requiresrelativepositioning
Nomattertheimplementationmethod,scrollspyrequirestheuseof position:relativeonthe
elementyou'respyingon.Inmostcasesthisisthe <body>.Whenscrollspyingonelementsotherthan
the <body>,besuretohavea heightsetand overflowy:scrollapplied.

Viadataattributes
Toeasilyaddscrollspybehaviortoyourtopbarnavigation,add dataspy="scroll"totheelement
youwanttospyon(mosttypicallythiswouldbethe <body>).Thenaddthe datatargetattribute
withtheIDorclassoftheparentelementofanyBootstrap .navcomponent.
body{
position:relative
}

<bodydataspy="scroll"datatarget="#navbarexample">
...
<divid="navbarexample">
<ulclass="navnavtabs"role="tablist">
...
</ul>
</div>
...
</body>

ViaJavaScript
Afteradding position:relativeinyourCSS,callthescrollspyviaJavaScript:
$('body').scrollspy({target:'#navbarexample'})

Methods
.scrollspy('refresh')
WhenusingscrollspyinconjunctionwithaddingorremovingofelementsfromtheDOM,you'llneedto
calltherefreshmethodlikeso:
$('[dataspy="scroll"]').each(function(){
var$spy=$(this).scrollspy('refresh')
})
http://getbootstrap.com/javascript/

17/51

7/5/2016

JavaScript Bootstrap

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin dataoffset="".
Name

type

default

description

offset

number

10

Pixelstooffsetfromtopwhencalculatingpositionofscroll.

Events
EventType

Description

activate.bs.scrollspy

Thiseventfireswheneveranewitembecomesactivatedbythescrollspy.

$('#myScrollspy').on('activate.bs.scrollspy',function(){
//dosomething
})

Togglabletabstab.js
Exampletabs
Addquick,dynamictabfunctionalitytotransitionthroughpanesoflocalcontent,evenviadropdown
menus.Nestedtabsarenotsupported.
EXAMPLE

Home

Profile

Dropdown

Rawdenimyouprobablyhaven'theardofthemjeanshortsAustin.Nesciunttofustumptownaliqua,
retrosynthmastercleanse.Mustacheclichetempor,williamsburgcarlesveganhelvetica.
Reprehenderitbutcherretrokeffiyehdreamcatchersynth.Cosbysweatereubanhmi,quiirureterry
richardsonexsquid.Aliquipplaceatsalviacillumiphone.Seitanaliquipquiscardiganamericanapparel,
butchervoluptatenisiqui.

Extendstabbednavigation
http://getbootstrap.com/javascript/

18/51

7/5/2016

JavaScript Bootstrap

Thispluginextendsthetabbednavigationcomponent(../components/#navtabs)toadd
tabbableareas.

Usage
EnabletabbabletabsviaJavaScript(eachtabneedstobeactivatedindividually):
$('#myTabsa').click(function(e){
e.preventDefault()
$(this).tab('show')
})

Youcanactivateindividualtabsinseveralways:
$('#myTabsa[href="#profile"]').tab('show')//Selecttabbyname
$('#myTabsa:first').tab('show')//Selectfirsttab
$('#myTabsa:last').tab('show')//Selectlasttab
$('#myTabsli:eq(2)a').tab('show')//Selectthirdtab(0indexed)

Markup
YoucanactivateataborpillnavigationwithoutwritinganyJavaScriptbysimplyspecifying data
toggle="tab"or datatoggle="pill"onanelement.Addingthe navand navtabsclassesto

thetab ulwillapplytheBootstraptabstyling(../components/#navtabs),whileaddingthe navand


navpillsclasseswillapplypillstyling(../components/#navpills).
<div>
<!Navtabs>
<ulclass="navnavtabs"role="tablist">
<lirole="presentation"class="active"><ahref="#home"aria
controls="home"role="tab"datatoggle="tab">Home</a></li>
<lirole="presentation"><ahref="#profile"ariacontrols="profile"
role="tab"datatoggle="tab">Profile</a></li>
<lirole="presentation"><ahref="#messages"ariacontrols="messages"
role="tab"datatoggle="tab">Messages</a></li>
<lirole="presentation"><ahref="#settings"ariacontrols="settings"
role="tab"datatoggle="tab">Settings</a></li>
</ul>
<!Tabpanes>
<divclass="tabcontent">
<divrole="tabpanel"class="tabpaneactive"id="home">...</div>
<divrole="tabpanel"class="tabpane"id="profile">...</div>
<divrole="tabpanel"class="tabpane"id="messages">...</div>
<divrole="tabpanel"class="tabpane"id="settings">...</div>
</div>
</div>

Fadeeffect

http://getbootstrap.com/javascript/

19/51

7/5/2016

JavaScript Bootstrap

Fadeeffect
Tomaketabsfadein,add .fadetoeach .tabpane.Thefirsttabpanemustalsohave .intomake
theinitialcontentvisible.
<divclass="tabcontent">
<divrole="tabpanel"class="tabpanefadeinactive"id="home">...
</div>
<divrole="tabpanel"class="tabpanefade"id="profile">...</div>
<divrole="tabpanel"class="tabpanefade"id="messages">...</div>
<divrole="tabpanel"class="tabpanefade"id="settings">...</div>
</div>

Methods
$().tab
Activatesatabelementandcontentcontainer.Tabshouldhaveeithera datatargetoran href
targetingacontainernodeintheDOM.Intheaboveexamples,thetabsarethe <a>swith data
toggle="tab"attributes.

.tab('show')
Selectsthegiventabandshowsitsassociatedcontent.Anyothertabthatwaspreviouslyselected
becomesunselectedanditsassociatedcontentishidden.Returnstothecallerbeforethetabpane
hasactuallybeenshown(i.e.beforethe shown.bs.tabeventoccurs).
$('#someTab').tab('show')

Events
Whenshowinganewtab,theeventsfireinthefollowingorder:
1. hide.bs.tab(onthecurrentactivetab)
2. show.bs.tab(onthetobeshowntab)
3. hidden.bs.tab(onthepreviousactivetab,thesameoneasforthe hide.bs.tabevent)
4. shown.bs.tab(onthenewlyactivejustshowntab,thesameoneasforthe show.bs.tab
event)
Ifnotabwasalreadyactive,thenthe hide.bs.taband hidden.bs.tabeventswillnotbefired.
EventType

Description

show.bs.tab

Thiseventfiresontabshow,butbeforethenewtabhasbeenshown.Use
event.targetand event.relatedTargettotargettheactivetaband
thepreviousactivetab(ifavailable)respectively.

shown.bs.tab

Thiseventfiresontabshowafteratabhasbeenshown.Use
event.targetand event.relatedTargettotargettheactivetaband
thepreviousactivetab(ifavailable)respectively.

http://getbootstrap.com/javascript/

20/51

7/5/2016

JavaScript Bootstrap

hide.bs.tab

Thiseventfireswhenanewtabistobeshown(andthusthepreviousactive
tabistobehidden).Use event.targetand event.relatedTargetto
targetthecurrentactivetabandthenewsoontobeactivetab,respectively.

hidden.bs.tab

Thiseventfiresafteranewtabisshown(andthusthepreviousactivetabis
hidden).Use event.targetand event.relatedTargettotargetthe
previousactivetabandthenewactivetab,respectively.

$('a[datatoggle="tab"]').on('shown.bs.tab',function(e){
e.target//newlyactivatedtab
e.relatedTarget//previousactivetab
})

Tooltipstooltip.js
InspiredbytheexcellentjQuery.tipsypluginwrittenbyJasonFrameTooltipsareanupdatedversion,
whichdon'trelyonimages,useCSS3foranimations,anddataattributesforlocaltitlestorage.
Tooltipswithzerolengthtitlesareneverdisplayed.

Examples
Hoveroverthelinksbelowtoseetooltips:
EXAMPLE

Tightpantsnextlevelkeffiyehyouprobablyhaven'theardofthem.Photoboothbeardrawdenim
letterpressveganmessengerbagstumptown.Farmtotableseitan,mcsweeney'sfixiesustainable
quinoa8bitamericanapparelhaveaterryrichardsonvinylchambray.Beardstumptown,cardigans
banhmilomothundercats.Tofubiodieselwilliamsburgmarfa,fourlokomcsweeney'scleansevegan
chambray.Areallyironicartisanwhateverkeytar,scenesterfarmtotablebanksyAustintwitterhandle
freegancredrawdenimsingleorigincoffeeviral.

Statictooltip
Fouroptionsareavailable:top,right,bottom,andleftaligned.
EXAMPLE

Tooltipontheleft

http://getbootstrap.com/javascript/

Tooltiponthetop

Tooltiponthebottom

21/51

7/5/2016

JavaScript Bootstrap

Tooltipontheright

Fourdirections
EXAMPLE

Tooltiponleft Tooltipontop Tooltiponbottom Tooltiponright

<buttontype="button"class="btnbtndefault"datatoggle="tooltip"data
placement="left"title="Tooltiponleft">Tooltiponleft</button>
<buttontype="button"class="btnbtndefault"datatoggle="tooltip"data
placement="top"title="Tooltipontop">Tooltipontop</button>
<buttontype="button"class="btnbtndefault"datatoggle="tooltip"data
placement="bottom"title="Tooltiponbottom">Tooltiponbottom</button>
<buttontype="button"class="btnbtndefault"datatoggle="tooltip"data
placement="right"title="Tooltiponright">Tooltiponright</button>

Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumust
initializethemyourself.
Onewaytoinitializealltooltipsonapagewouldbetoselectthembytheir datatoggle
attribute:
$(function(){
$('[datatoggle="tooltip"]').tooltip()
})

Usage
Thetooltipplugingeneratescontentandmarkupondemand,andbydefaultplacestooltipsaftertheir
triggerelement.
TriggerthetooltipviaJavaScript:
$('#example').tooltip(options)

Markup
http://getbootstrap.com/javascript/

22/51

7/5/2016

JavaScript Bootstrap

Therequiredmarkupforatooltipisonlya dataattributeand titleontheHTMLelementyouwish


tohaveatooltip.Thegeneratedmarkupofatooltipisrathersimple,thoughitdoesrequireaposition
(bydefault,setto topbytheplugin).
<!HTMLtowrite>
<ahref="#"datatoggle="tooltip"title="Sometooltiptext!">Hoverover
me</a>
<!Generatedmarkupbytheplugin>
<divclass="tooltiptop"role="tooltip">
<divclass="tooltiparrow"></div>
<divclass="tooltipinner">
Sometooltiptext!
</div>
</div>

Multiplelinelinks
Sometimesyouwanttoaddatooltiptoahyperlinkthatwrapsmultiplelines.Thedefault
behaviorofthetooltippluginistocenterithorizontallyandvertically.Add whitespace:
nowraptoyouranchorstoavoidthis.

Tooltipsinbuttongroups,inputgroups,andtablesrequirespecialsetting
Whenusingtooltipsonelementswithina .btngrouporan .inputgroup,orontable
relatedelements( <td>, <th>, <tr>, <thead>, <tbody>, <tfoot>),you'llhavetospecify
theoption container:'body'(documentedbelow)toavoidunwantedsideeffects(suchas
theelementgrowingwiderand/orlosingitsroundedcornerswhenthetooltipistriggered).

Don'ttrytoshowtooltipsonhiddenelements
Invoking $(...).tooltip('show')whenthetargetelementis display:nonewillcause
thetooltiptobeincorrectlypositioned.

Accessibletooltipsforkeyboardandassistivetechnologyusers
Forusersnavigatingwithakeyboard,andinparticularusersofassistivetechnologies,you
shouldonlyaddtooltipstokeyboardfocusableelementssuchaslinks,formcontrols,orany
arbitraryelementwitha tabindex="0"attribute.

Tooltipsondisabledelementsrequirewrapperelements
Toaddatooltiptoa disabledor .disabledelement,puttheelementinsideofa <div>and
applythetooltiptothat <div>instead.
http://getbootstrap.com/javascript/

23/51

7/5/2016

JavaScript Bootstrap

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin dataanimation="".
Name

Type

Default

Description

animation

boolean

true

ApplyaCSSfadetransitiontothetooltip

container

string|false

false

Appendsthetooltiptoaspecificelement.
Example: container:'body'.Thisoptionis
particularlyusefulinthatitallowsyouto
positionthetooltipintheflowofthedocument
nearthetriggeringelementwhichwillprevent
thetooltipfromfloatingawayfromthe
triggeringelementduringawindowresize.

delay

number|
object

Delayshowingandhidingthetooltip(ms)
doesnotapplytomanualtriggertype
Ifanumberissupplied,delayisappliedtoboth
hide/show
Objectstructureis: delay:{"show":500,
"hide":100}

html

boolean

false

InsertHTMLintothetooltip.Iffalse,jQuery's
textmethodwillbeusedtoinsertcontent
intotheDOM.Usetextifyou'reworriedabout
XSSattacks.

placement

string|
function

'top'

Howtopositionthetooltiptop|bottom|left|
right|auto.
When"auto"isspecified,itwilldynamically
reorientthetooltip.Forexample,ifplacement
is"autoleft",thetooltipwilldisplaytotheleft
whenpossible,otherwiseitwilldisplayright.
Whenafunctionisusedtodeterminethe
placement,itiscalledwiththetooltipDOM
nodeasitsfirstargumentandthetriggering
elementDOMnodeasitssecond.The this
contextissettothetooltipinstance.

selector

string

http://getbootstrap.com/javascript/

false

Ifaselectorisprovided,tooltipobjectswillbe
delegatedtothespecifiedtargets.Inpractice,
thisisusedtoenabledynamicHTMLcontent
tohavetooltipsadded.Seethis
24/51

7/5/2016

JavaScript Bootstrap

(https://github.com/twbs/bootstrap/issues/4215)
andaninformativeexample
(http://jsbin.com/zopod/1/edit).
template

string

'<div
class="tooltip"
role="tooltip">
<div
class="tooltip

BaseHTMLtousewhencreatingthetooltip.
Thetooltip's titlewillbeinjectedintothe
.tooltipinner.
.tooltiparrowwillbecomethetooltip's

arrow"></div>

arrow.

<div

Theoutermostwrapperelementshouldhave

class="tooltip the .tooltipclass.


inner"></div>
</div>'

title

string|
function

''

Defaulttitlevalueif titleattributeisn't
present.
Ifafunctionisgiven,itwillbecalledwithits
thisreferencesettotheelementthatthe
tooltipisattachedto.

trigger

string

'hoverfocus'

Howtooltipistriggeredclick|hover|focus|
manual.Youmaypassmultipletriggers
separatethemwithaspace. manualcannot
becombinedwithanyothertrigger.

viewport

string|
object|
function

{selector:'body',
padding:0}

Keepsthetooltipwithintheboundsofthis
element.Example: viewport:'#viewport'
or {"selector":"#viewport",
"padding":0}

Ifafunctionisgiven,itiscalledwiththe
triggeringelementDOMnodeasitsonly
argument.The thiscontextissettothe
tooltipinstance.

Dataattributesforindividualtooltips
Optionsforindividualtooltipscanalternativelybespecifiedthroughtheuseofdataattributes,as
explainedabove.

Methods
$().tooltip(options)
http://getbootstrap.com/javascript/

25/51

7/5/2016

JavaScript Bootstrap

Attachesatooltiphandlertoanelementcollection.

.tooltip('show')
Revealsanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenshown(i.e.
beforethe shown.bs.tooltipeventoccurs).Thisisconsidereda"manual"triggeringofthetooltip.
Tooltipswithzerolengthtitlesareneverdisplayed.
$('#element').tooltip('show')

.tooltip('hide')
Hidesanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenhidden(i.e.
beforethe hidden.bs.tooltipeventoccurs).Thisisconsidereda"manual"triggeringofthetooltip.
$('#element').tooltip('hide')

.tooltip('toggle')
Togglesanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenshownor
hidden(i.e.beforethe shown.bs.tooltipor hidden.bs.tooltipeventoccurs).Thisisconsidered
a"manual"triggeringofthetooltip.
$('#element').tooltip('toggle')

.tooltip('destroy')
Hidesanddestroysanelement'stooltip.Tooltipsthatusedelegation(whicharecreatedusingthe
selectoroption)cannotbeindividuallydestroyedondescendanttriggerelements.
$('#element').tooltip('destroy')

Events
EventType

Description

show.bs.tooltip

Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.

shown.bs.tooltip

Thiseventisfiredwhenthetooltiphasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).

hide.bs.tooltip

Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.

hidden.bs.tooltip

Thiseventisfiredwhenthetooltiphasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).

inserted.bs.tooltip

Thiseventisfiredafterthe show.bs.tooltipeventwhenthetooltip
templatehasbeenaddedtotheDOM.

http://getbootstrap.com/javascript/

26/51

7/5/2016

JavaScript Bootstrap

$('#myTooltip').on('hidden.bs.tooltip',function(){
//dosomething
})

Popoverspopover.js
Addsmalloverlaysofcontent,likethoseontheiPad,toanyelementforhousingsecondaryinformation.
Popoverswhosebothtitleandcontentarezerolengthareneverdisplayed.

Plugindependency
PopoversrequirethetooltipplugintobeincludedinyourversionofBootstrap.

Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumust
initializethemyourself.
Onewaytoinitializeallpopoversonapagewouldbetoselectthembytheir datatoggle
attribute:
$(function(){
$('[datatoggle="popover"]').popover()
})

Popoversinbuttongroups,inputgroups,andtablesrequirespecialsetting
Whenusingpopoversonelementswithina .btngrouporan .inputgroup,orontable
relatedelements( <td>, <th>, <tr>, <thead>, <tbody>, <tfoot>),you'llhavetospecify
theoption container:'body'(documentedbelow)toavoidunwantedsideeffects(suchas
theelementgrowingwiderand/orlosingitsroundedcornerswhenthepopoveristriggered).

Don'ttrytoshowpopoversonhiddenelements
Invoking $(...).popover('show')whenthetargetelementis display:nonewillcause
thepopovertobeincorrectlypositioned.

Popoversondisabledelementsrequirewrapperelements
http://getbootstrap.com/javascript/

27/51

7/5/2016

JavaScript Bootstrap

Toaddapopovertoa disabledor .disabledelement,puttheelementinsideofa <div>


andapplythepopovertothat <div>instead.

Multiplelinelinks
Sometimesyouwanttoaddapopovertoahyperlinkthatwrapsmultiplelines.Thedefault
behaviorofthepopoverpluginistocenterithorizontallyandvertically.Add whitespace:
nowraptoyouranchorstoavoidthis.

Examples
Staticpopover
Fouroptionsareavailable:top,right,bottom,andleftaligned.
EXAMPLE

Popovertop

Popoverright

Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.

Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.

Popoverbottom

Popoverleft

Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.

Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.

Livedemo
EXAMPLE

Clicktotogglepopover

http://getbootstrap.com/javascript/

28/51

7/5/2016

JavaScript Bootstrap

<buttontype="button"class="btnbtnlgbtndanger"datatoggle="popover"
title="Popovertitle"datacontent="Andhere'ssomeamazingcontent.It's
veryengaging.Right?">Clicktotogglepopover</button>

Fourdirections
EXAMPLE

Popoveronright Popoverontop Popoveronbottom Popoveronleft

<buttontype="button"class="btnbtndefault"datacontainer="body"data
toggle="popover"dataplacement="left"datacontent="Vivamussagittislacus
velauguelaoreetrutrumfaucibus.">
Popoveronleft
</button>
<buttontype="button"class="btnbtndefault"datacontainer="body"data
toggle="popover"dataplacement="top"datacontent="Vivamussagittislacus
velauguelaoreetrutrumfaucibus.">
Popoverontop
</button>
<buttontype="button"class="btnbtndefault"datacontainer="body"data
toggle="popover"dataplacement="bottom"datacontent="Vivamus
sagittislacusvelauguelaoreetrutrumfaucibus.">
Popoveronbottom
</button>
<buttontype="button"class="btnbtndefault"datacontainer="body"data
toggle="popover"dataplacement="right"datacontent="Vivamussagittislacus
velauguelaoreetrutrumfaucibus.">
Popoveronright
</button>

Dismissonnextclick
Usethe focustriggertodismisspopoversonthenextclickthattheusermakes.

Specificmarkuprequiredfordismissonnextclick
Forpropercrossbrowserandcrossplatformbehavior,youmustusethe <a>tag,notthe
<button>tag,andyoualsomustincludethe role="button"and tabindex

(https://developer.mozilla.org/enUS/docs/Web/HTML/Global_attributes#tabindex)attributes.

EXAMPLE

Dismissiblepopover
http://getbootstrap.com/javascript/

29/51

7/5/2016

JavaScript Bootstrap

<atabindex="0"class="btnbtnlgbtndanger"role="button"data
toggle="popover"datatrigger="focus"title="Dismissiblepopover"data
content="Andhere'ssomeamazingcontent.It'sveryengaging.
Right?">Dismissiblepopover</a>

Usage
EnablepopoversviaJavaScript:
$('#example').popover(options)

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin dataanimation="".
Name

Type

Default

Description

animation

boolean

true

ApplyaCSSfadetransitiontothepopover

container

string|false

false

Appendsthepopovertoaspecificelement.
Example: container:'body'.Thisoptionis
particularlyusefulinthatitallowsyouto
positionthepopoverintheflowofthe
documentnearthetriggeringelementwhich
willpreventthepopoverfromfloatingaway
fromthetriggeringelementduringawindow
resize.

content

string|
function

''

Defaultcontentvalueif datacontent
attributeisn'tpresent.
Ifafunctionisgiven,itwillbecalledwithits
thisreferencesettotheelementthatthe
popoverisattachedto.

delay

number|
object

Delayshowingandhidingthepopover(ms)
doesnotapplytomanualtriggertype
Ifanumberissupplied,delayisappliedtoboth
hide/show
Objectstructureis: delay:{"show":500,
"hide":100}

html

boolean

http://getbootstrap.com/javascript/

false

InsertHTMLintothepopover.Iffalse,jQuery's
textmethodwillbeusedtoinsertcontent
30/51

7/5/2016

JavaScript Bootstrap

intotheDOM.Usetextifyou'reworriedabout
XSSattacks.
placement

string|
function

'right'

Howtopositionthepopovertop|bottom|left
|right|auto.
When"auto"isspecified,itwilldynamically
reorientthepopover.Forexample,ifplacement
is"autoleft",thepopoverwilldisplaytotheleft
whenpossible,otherwiseitwilldisplayright.
Whenafunctionisusedtodeterminethe
placement,itiscalledwiththepopoverDOM
nodeasitsfirstargumentandthetriggering
elementDOMnodeasitssecond.The this
contextissettothepopoverinstance.

selector

string

template

string

false

'<div
class="popover"
role="tooltip">
<div
class="arrow">
</div><h3
class="popover
title"></h3>

Ifaselectorisprovided,popoverobjectswillbe
delegatedtothespecifiedtargets.Inpractice,
thisisusedtoenabledynamicHTMLcontent
tohavepopoversadded.Seethis
(https://github.com/twbs/bootstrap/issues/4215)
andaninformativeexample
(http://jsbin.com/zopod/1/edit).
BaseHTMLtousewhencreatingthepopover.
Thepopover's titlewillbeinjectedintothe
.popovertitle.

Thepopover's contentwillbeinjectedinto
the .popovercontent.
.arrowwillbecomethepopover'sarrow.

Theoutermostwrapperelementshouldhave
class="popover the .popoverclass.
<div

content"></div>
</div>'

title

string|
function

''

Defaulttitlevalueif titleattributeisn't
present.
Ifafunctionisgiven,itwillbecalledwithits
thisreferencesettotheelementthatthe
popoverisattachedto.

trigger

string

'click'

Howpopoveristriggeredclick|hover|focus
|manual.Youmaypassmultipletriggers
separatethemwithaspace. manualcannot
becombinedwithanyothertrigger.

http://getbootstrap.com/javascript/

31/51

7/5/2016

viewport

JavaScript Bootstrap

string|
object|
function

{selector:'body',
padding:0}

Keepsthepopoverwithintheboundsofthis
element.Example: viewport:'#viewport'
or {"selector":"#viewport",
"padding":0}

Ifafunctionisgiven,itiscalledwiththe
triggeringelementDOMnodeasitsonly
argument.The thiscontextissettothe
popoverinstance.

Dataattributesforindividualpopovers
Optionsforindividualpopoverscanalternativelybespecifiedthroughtheuseofdataattributes,
asexplainedabove.

Methods
$().popover(options)
Initializespopoversforanelementcollection.

.popover('show')
Revealsanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenshown
(i.e.beforethe shown.bs.popovereventoccurs).Thisisconsidereda"manual"triggeringofthe
popover.Popoverswhosebothtitleandcontentarezerolengthareneverdisplayed.
$('#element').popover('show')

.popover('hide')
Hidesanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenhidden
(i.e.beforethe hidden.bs.popovereventoccurs).Thisisconsidereda"manual"triggeringofthe
popover.
$('#element').popover('hide')

.popover('toggle')
Togglesanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenshown
orhidden(i.e.beforethe shown.bs.popoveror hidden.bs.popovereventoccurs).Thisis
considereda"manual"triggeringofthepopover.
$('#element').popover('toggle')

.popover('destroy')

http://getbootstrap.com/javascript/

32/51

7/5/2016

JavaScript Bootstrap

Hidesanddestroysanelement'spopover.Popoversthatusedelegation(whicharecreatedusingthe
selectoroption)cannotbeindividuallydestroyedondescendanttriggerelements.
$('#element').popover('destroy')

Events
EventType

Description

show.bs.popover

Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.

shown.bs.popover

Thiseventisfiredwhenthepopoverhasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).

hide.bs.popover

Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.

hidden.bs.popover

Thiseventisfiredwhenthepopoverhasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).

inserted.bs.popover

Thiseventisfiredafterthe show.bs.popovereventwhenthepopover
templatehasbeenaddedtotheDOM.

$('#myPopover').on('hidden.bs.popover',function(){
//dosomething
})

Alertmessagesalert.js
Examplealerts
Adddismissfunctionalitytoallalertmessageswiththisplugin.
Whenusinga .closebutton,itmustbethefirstchildofthe .alertdismissibleandnotext
contentmaycomebeforeitinthemarkup.
EXAMPLE

Holyguacamole!Bestcheckyoself,you'renotlookingtoogood.

Ohsnap!Yougotanerror!

http://getbootstrap.com/javascript/

33/51

7/5/2016

JavaScript Bootstrap

Changethisandthatandtryagain.Duismollis,estnoncommodoluctus,nisieratporttitor
ligula,egetlaciniaodiosemnecelit.Crasmattisconsecteturpurussitametfermentum.
Takethisaction Ordothis

Usage
Justadd datadismiss="alert"toyourclosebuttontoautomaticallygiveanalertclosefunctionality.
ClosinganalertremovesitfromtheDOM.
<buttontype="button"class="close"datadismiss="alert"aria
label="Close">
<spanariahidden="true">&times</span>
</button>

Tohaveyouralertsuseanimationwhenclosing,makesuretheyhavethe .fadeand .inclasses


alreadyappliedtothem.

Methods
$().alert()
Makesanalertlistenforclickeventsondescendantelementswhichhavethe datadismiss="alert"
attribute.(Notnecessarywhenusingthedataapi'sautoinitialization.)

$().alert('close')
ClosesanalertbyremovingitfromtheDOM.Ifthe .fadeand .inclassesarepresentonthe
element,thealertwillfadeoutbeforeitisremoved.

Events
Bootstrap'salertpluginexposesafeweventsforhookingintoalertfunctionality.
EventType

Description

close.bs.alert

Thiseventfiresimmediatelywhenthe closeinstancemethodiscalled.

closed.bs.alert

Thiseventisfiredwhenthealerthasbeenclosed(willwaitforCSS
transitionstocomplete).

$('#myAlert').on('closed.bs.alert',function(){
//dosomething
})

http://getbootstrap.com/javascript/

34/51

7/5/2016

JavaScript Bootstrap

Buttonsbutton.js
Domorewithbuttons.Controlbuttonstatesorcreategroupsofbuttonsformore
componentsliketoolbars.

Crossbrowsercompatibility
Firefoxpersistsformcontrolstates(disablednessandcheckedness)acrosspageloads
(https://github.com/twbs/bootstrap/issues/793).Aworkaroundforthisistouse
autocomplete="off".SeeMozillabug#654072(https://bugzilla.mozilla.org/show_bug.cgi?
id=654072).

Stateful
Add dataloadingtext="Loading..."tousealoadingstateonabutton.
Thisfeatureisdeprecatedsincev3.3.6andhasbeenremovedinv4.

Usewhicheverstateyoulike!
Forthesakeofthisdemonstration,weareusing dataloadingtextand
$().button('loading'),butthat'snottheonlystateyoucanuse.Seemoreonthisbelowin

the $().button(string)documentation.

EXAMPLE

Loadingstate

<buttontype="button"id="myButton"dataloadingtext="Loading..."
class="btnbtnprimary"autocomplete="off">
Loadingstate
</button>
<script>
$('#myButton').on('click',function(){
var$btn=$(this).button('loading')
//businesslogic...
$btn.button('reset')
})
</script>

Singletoggle
http://getbootstrap.com/javascript/

35/51

7/5/2016

JavaScript Bootstrap

Add datatoggle="button"toactivatetogglingonasinglebutton.

Pretoggledbuttonsneed .activeand ariapressed="true"


Forpretoggledbuttons,youmustaddthe .activeclassandthe ariapressed="true"
attributetothe buttonyourself.

EXAMPLE

Singletoggle

<buttontype="button"class="btnbtnprimary"datatoggle="button"aria
pressed="false"autocomplete="off">
Singletoggle
</button>

Checkbox/Radio
Add datatoggle="buttons"toa .btngroupcontainingcheckboxorradioinputstoenable
togglingintheirrespectivestyles.

Preselectedoptionsneed .active
Forpreselectedoptions,youmustaddthe .activeclasstotheinput's labelyourself.

Visualcheckedstateonlyupdatedonclick
Ifthecheckedstateofacheckboxbuttonisupdatedwithoutfiringa clickeventonthebutton
(e.g.via <inputtype="reset">orviasettingthe checkedpropertyoftheinput),youwill
needtotogglethe .activeclassontheinput's labelyourself.

EXAMPLE

Checkbox1(prechecked)

http://getbootstrap.com/javascript/

Checkbox2

Checkbox3

36/51

7/5/2016

JavaScript Bootstrap

<divclass="btngroup"datatoggle="buttons">
<labelclass="btnbtnprimaryactive">
<inputtype="checkbox"autocomplete="off"checked>Checkbox1(pre
checked)
</label>
<labelclass="btnbtnprimary">
<inputtype="checkbox"autocomplete="off">Checkbox2
</label>
<labelclass="btnbtnprimary">
<inputtype="checkbox"autocomplete="off">Checkbox3
</label>
</div>

EXAMPLE

Radio1(preselected)

Radio2

Radio3

<divclass="btngroup"datatoggle="buttons">
<labelclass="btnbtnprimaryactive">
<inputtype="radio"name="options"id="option1"autocomplete="off"
checked>Radio1(preselected)
</label>
<labelclass="btnbtnprimary">
<inputtype="radio"name="options"id="option2"autocomplete="off">
Radio2
</label>
<labelclass="btnbtnprimary">
<inputtype="radio"name="options"id="option3"autocomplete="off">
Radio3
</label>
</div>

Methods
$().button('toggle')
Togglespushstate.Givesthebuttontheappearancethatithasbeenactivated.

$().button('reset')
Resetsbuttonstateswapstexttooriginaltext.Thismethodisasynchronousandreturnsbefore
theresettinghasactuallycompleted.

$().button(string)
Swapstexttoanydatadefinedtextstate.

http://getbootstrap.com/javascript/

37/51

7/5/2016

JavaScript Bootstrap

<buttontype="button"id="myStateButton"datacompletetext="finished!"
class="btnbtnprimary"autocomplete="off">
...
</button>
<script>
$('#myStateButton').on('click',function(){
$(this).button('complete')//buttontextwillbe"finished!"
})
</script>

Collapsecollapse.js
Flexiblepluginthatutilizesahandfulofclassesforeasytogglebehavior.

Plugindependency
CollapserequiresthetransitionsplugintobeincludedinyourversionofBootstrap.

Example
Clickthebuttonsbelowtoshowandhideanotherelementviaclasschanges:
.collapsehidescontent
.collapsingisappliedduringtransitions
.collapse.inshowscontent

Youcanusealinkwiththe hrefattribute,orabuttonwiththe datatargetattribute.Inbothcases,


the datatoggle="collapse"isrequired.
EXAMPLE

Linkwithhref Buttonwithdatatarget

http://getbootstrap.com/javascript/

38/51

7/5/2016

JavaScript Bootstrap

<aclass="btnbtnprimary"role="button"datatoggle="collapse"
href="#collapseExample"ariaexpanded="false"aria
controls="collapseExample">
Linkwithhref
</a>
<buttonclass="btnbtnprimary"type="button"datatoggle="collapse"data
target="#collapseExample"ariaexpanded="false"aria
controls="collapseExample">
Buttonwithdatatarget
</button>
<divclass="collapse"id="collapseExample">
<divclass="well">
...
</div>
</div>

Accordionexample
Extendthedefaultcollapsebehaviortocreateanaccordionwiththepanelcomponent.
EXAMPLE

CollapsibleGroupItem#1
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamusterryrichardsonadsquid.3
wolfmoonofficiaaute,noncupidatatskateboarddolorbrunch.Foodtruckquinoanesciunt
laborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigin
coffeenullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeerlaborewes
andersoncrednesciuntsapienteeaproident.Adveganexcepteurbutchervicelomo.Leggings
occaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven'theard
ofthemaccusamuslaboresustainableVHS.

CollapsibleGroupItem#2
CollapsibleGroupItem#3

http://getbootstrap.com/javascript/

39/51

7/5/2016

JavaScript Bootstrap

<divclass="panelgroup"id="accordion"role="tablist"aria
multiselectable="true">
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingOne">
<h4class="paneltitle">
<arole="button"datatoggle="collapse"dataparent="#accordion"
href="#collapseOne"ariaexpanded="true"ariacontrols="collapseOne">
CollapsibleGroupItem#1
</a>
</h4>
</div>
<divid="collapseOne"class="panelcollapsecollapsein"role="tabpanel"
arialabelledby="headingOne">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamus
terryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeer
laborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenim
aestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingTwo">
<h4class="paneltitle">
<aclass="collapsed"role="button"datatoggle="collapse"data
parent="#accordion"href="#collapseTwo"ariaexpanded="false"aria
controls="collapseTwo">
CollapsibleGroupItem#2
</a>
</h4>
</div>
<divid="collapseTwo"class="panelcollapsecollapse"role="tabpanel"
arialabelledby="headingTwo">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamus
terryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeer
laborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenim
aestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingThree">
<h4class="paneltitle">
http://getbootstrap.com/javascript/

40/51

7/5/2016

JavaScript Bootstrap

<aclass="collapsed"role="button"datatoggle="collapse"data
parent="#accordion"href="#collapseThree"ariaexpanded="false"aria
controls="collapseThree">
CollapsibleGroupItem#3
</a>
</h4>
</div>
<divid="collapseThree"class="panelcollapsecollapse"role="tabpanel"
arialabelledby="headingThree">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamus
terryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeer
laborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenim
aestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
</div>

It'salsopossibletoswapout .panelbodyswith .listgroups.

Collapsiblelistgroup

Makeexpand/collapsecontrolsaccessible
Besuretoadd ariaexpandedtothecontrolelement.Thisattributeexplicitlydefinesthe
currentstateofthecollapsibleelementtoscreenreadersandsimilarassistivetechnologies.If
thecollapsibleelementisclosedbydefault,itshouldhaveavalueof aria
expanded="false".Ifyou'vesetthecollapsibleelementtobeopenbydefaultusingthe in
class,set ariaexpanded="true"onthecontrolinstead.Thepluginwillautomaticallytoggle
thisattributebasedonwhetherornotthecollapsibleelementhasbeenopenedorclosed.
Additionally,ifyourcontrolelementistargettingasinglecollapsibleelementi.e.the data
targetattributeispointingtoan idselectoryoumayaddanadditional ariacontrols

attributetothecontrolelement,containingthe idofthecollapsibleelement.Modernscreen
readersandsimilarassistivetechnologiesmakeuseofthisattributetoprovideuserswith
additionalshortcutstonavigatedirectlytothecollapsibleelementitself.

Usage
Thecollapsepluginutilizesafewclassestohandletheheavylifting:
.collapsehidesthecontent
.collapse.inshowsthecontent
http://getbootstrap.com/javascript/

41/51

7/5/2016

JavaScript Bootstrap

.collapsingisaddedwhenthetransitionstarts,andremovedwhenitfinishes

Theseclassescanbefoundin componentanimations.less.

Viadataattributes
Justadd datatoggle="collapse"anda datatargettotheelementtoautomaticallyassign
controlofacollapsibleelement.The datatargetattributeacceptsaCSSselectortoapplythe
collapseto.Besuretoaddtheclass collapsetothecollapsibleelement.Ifyou'dlikeittodefault
open,addtheadditionalclass in.
Toaddaccordionlikegroupmanagementtoacollapsiblecontrol,addthedataattribute data
parent="#selector".Refertothedemotoseethisinaction.

ViaJavaScript
Enablemanuallywith:
$('.collapse').collapse()

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin dataparent="".
Name

type

default

description

parent

selector

false

Ifaselectorisprovided,thenallcollapsibleelements
underthespecifiedparentwillbeclosedwhenthis
collapsibleitemisshown.(similartotraditionalaccordion
behaviorthisisdependentonthe panelclass)

toggle

boolean

true

Togglesthecollapsibleelementoninvocation

Methods
.collapse(options)
Activatesyourcontentasacollapsibleelement.Acceptsanoptionaloptions object.
$('#myCollapsible').collapse({
toggle:false
})

.collapse('toggle')
Togglesacollapsibleelementtoshownorhidden.Returnstothecallerbeforethecollapsible
elementhasactuallybeenshownorhidden(i.e.beforethe shown.bs.collapseor
hidden.bs.collapseeventoccurs).
http://getbootstrap.com/javascript/

42/51

7/5/2016

JavaScript Bootstrap

.collapse('show')
Showsacollapsibleelement.Returnstothecallerbeforethecollapsibleelementhasactually
beenshown(i.e.beforethe shown.bs.collapseeventoccurs).

.collapse('hide')
Hidesacollapsibleelement.Returnstothecallerbeforethecollapsibleelementhasactuallybeen
hidden(i.e.beforethe hidden.bs.collapseeventoccurs).

Events
Bootstrap'scollapseclassexposesafeweventsforhookingintocollapsefunctionality.
EventType

Description

show.bs.collapse

Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.

shown.bs.collapse

Thiseventisfiredwhenacollapseelementhasbeenmadevisibletothe
user(willwaitforCSStransitionstocomplete).

hide.bs.collapse

Thiseventisfiredimmediatelywhenthe hidemethodhasbeencalled.

hidden.bs.collapse

Thiseventisfiredwhenacollapseelementhasbeenhiddenfromtheuser
(willwaitforCSStransitionstocomplete).

$('#myCollapsible').on('hidden.bs.collapse',function(){
//dosomething
})

Carouselcarousel.js
Aslideshowcomponentforcyclingthroughelements,likeacarousel.Nestedcarouselsarenot
supported.

Examples

http://getbootstrap.com/javascript/

43/51

7/5/2016

JavaScript Bootstrap

EXAMPLE

Firstslide

http://getbootstrap.com/javascript/

44/51

7/5/2016

JavaScript Bootstrap

<divid="carouselexamplegeneric"class="carouselslide"data
ride="carousel">
<!Indicators>
<olclass="carouselindicators">
<lidatatarget="#carouselexamplegeneric"dataslideto="0"
class="active"></li>
<lidatatarget="#carouselexamplegeneric"dataslideto="1"></li>
<lidatatarget="#carouselexamplegeneric"dataslideto="2"></li>
</ol>
<!Wrapperforslides>
<divclass="carouselinner"role="listbox">
<divclass="itemactive">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
...
</div>
</div>
<divclass="item">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
...
</div>
</div>
...
</div>
<!Controls>
<aclass="leftcarouselcontrol"href="#carouselexamplegeneric"
role="button"dataslide="prev">
<spanclass="glyphiconglyphiconchevronleft"ariahidden="true">
</span>
<spanclass="sronly">Previous</span>
</a>
<aclass="rightcarouselcontrol"href="#carouselexamplegeneric"
role="button"dataslide="next">
<spanclass="glyphiconglyphiconchevronright"ariahidden="true">
</span>
<spanclass="sronly">Next</span>
</a>
</div>

Accessibilityissue
Thecarouselcomponentisgenerallynotcompliantwithaccessibilitystandards.Ifyouneedto
becompliant,pleaseconsiderotheroptionsforpresentingyourcontent.

TransitionanimationsnotsupportedinInternetExplorer8&9

http://getbootstrap.com/javascript/

45/51

7/5/2016

JavaScript Bootstrap

BootstrapexclusivelyusesCSS3foritsanimations,butInternetExplorer8&9don'tsupportthe
necessaryCSSproperties.Thus,therearenoslidetransitionanimationswhenusingthese
browsers.WehaveintentionallydecidednottoincludejQuerybasedfallbacksforthe
transitions.

Initialactiveelementrequired
The .activeclassneedstobeaddedtooneoftheslides.Otherwise,thecarouselwillnotbe
visible.

Glyphiconiconsnotnecessary
The .glyphicon.glyphiconchevronleftand .glyphicon.glyphiconchevronright
classesarenotnecessarilyneededforthecontrols.Bootstrapprovides .iconprevand
.iconnextasplainunicodealternatives.

Optionalcaptions
Addcaptionstoyourslideseasilywiththe .carouselcaptionelementwithinany .item.Placejust
aboutanyoptionalHTMLwithinthereanditwillbeautomaticallyalignedandformatted.
EXAMPLE

900x500

Firstslidelabel
Nullavitaeelitlibero,apharetraauguemollisinterdum.

http://getbootstrap.com/javascript/

46/51

7/5/2016

JavaScript Bootstrap

<divclass="item">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
<h3>...</h3>
<p>...</p>
</div>
</div>

Usage
Multiplecarousels
Carouselsrequiretheuseofan idontheoutermostcontainer(the .carousel)forcarouselcontrols
tofunctionproperly.Whenaddingmultiplecarousels,orwhenchangingacarousel's id,besureto
updatetherelevantcontrols.

Viadataattributes
Usedataattributestoeasilycontrolthepositionofthecarousel. dataslideacceptsthekeywords
prevor next,whichalterstheslidepositionrelativetoitscurrentposition.Alternatively,use data
slidetotopassarawslideindextothecarousel dataslideto="2",whichshiftstheslide
positiontoaparticularindexbeginningwith 0.
The dataride="carousel"attributeisusedtomarkacarouselasanimatingstartingatpageload.It
cannotbeusedincombinationwith(redundantandunnecessary)explicitJavaScript
initializationofthesamecarousel.

ViaJavaScript
Callcarouselmanuallywith:
$('.carousel').carousel()

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin datainterval="".
Name

type

default

description

interval

number

5000

Theamountoftimetodelaybetweenautomatically
cyclinganitem.Iffalse,carouselwillnotautomatically
cycle.

pause

string

"hover"

Pausesthecyclingofthecarouselonmouseenterand
resumesthecyclingofthecarouselonmouseleave.

wrap

boolean

true

Whetherthecarouselshouldcyclecontinuouslyorhave
hardstops.

http://getbootstrap.com/javascript/

47/51

7/5/2016

JavaScript Bootstrap

keyboard

boolean

true

Whetherthecarouselshouldreacttokeyboardevents.

Methods
.carousel(options)
Initializesthecarouselwithanoptionaloptions objectandstartscyclingthroughitems.
$('.carousel').carousel({
interval:2000
})

.carousel('cycle')
Cyclesthroughthecarouselitemsfromlefttoright.

.carousel('pause')
Stopsthecarouselfromcyclingthroughitems.

.carousel(number)
Cyclesthecarouseltoaparticularframe(0based,similartoanarray).

.carousel('prev')
Cyclestothepreviousitem.

.carousel('next')
Cyclestothenextitem.

Events
Bootstrap'scarouselclassexposestwoeventsforhookingintocarouselfunctionality.
Botheventshavethefollowingadditionalproperties:
direction:Thedirectioninwhichthecarouselissliding(either "left"or "right").
relatedTarget:TheDOMelementthatisbeingslidintoplaceastheactiveitem.

Allcarouseleventsarefiredatthecarouselitself(i.e.atthe <divclass="carousel">).
EventType

Description

slide.bs.carousel

Thiseventfiresimmediatelywhenthe slideinstancemethodisinvoked.

slid.bs.carousel

Thiseventisfiredwhenthecarouselhascompleteditsslidetransition.

$('#myCarousel').on('slide.bs.carousel',function(){
//dosomething
})
http://getbootstrap.com/javascript/

48/51

7/5/2016

JavaScript Bootstrap

Affixaffix.js
Example
Theaffixplugintoggles position:fixedonandoff,emulatingtheeffectfoundwith position:
sticky(https://developer.mozilla.org/enUS/docs/Web/CSS/position#Sticky_positioning).The
subnavigationontherightisalivedemooftheaffixplugin.

Usage
UsetheaffixpluginviadataattributesormanuallywithyourownJavaScript.Inbothsituations,you
mustprovideCSSforthepositioningandwidthofyouraffixedcontent.
Note:Donotusetheaffixpluginonanelementcontainedinarelativelypositionedelement,suchasa
pulledorpushedcolumn,duetoaSafarirenderingbug
(https://github.com/twbs/bootstrap/issues/12126).

PositioningviaCSS
Theaffixplugintogglesbetweenthreeclasses,eachrepresentingaparticularstate: .affix, .affix
top,and .affixbottom.Youmustprovidethestyles,withtheexceptionof position:fixedon
.affix,fortheseclassesyourself(independentofthisplugin)tohandletheactualpositions.
Here'showtheaffixpluginworks:
1.Tostart,thepluginadds .affixtoptoindicatetheelementisinitstopmostposition.Atthis
pointnoCSSpositioningisrequired.
2.Scrollingpasttheelementyouwantaffixedshouldtriggertheactualaffixing.Thisiswhere
.affixreplaces .affixtopandsets position:fixed(providedbyBootstrap'sCSS).
3.Ifabottomoffsetisdefined,scrollingpastitshouldreplace .affixwith .affixbottom.Since
offsetsareoptional,settingonerequiresyoutosettheappropriateCSS.Inthiscase,add
position:absolutewhennecessary.ThepluginusesthedataattributeorJavaScriptoption
todeterminewheretopositiontheelementfromthere.
FollowtheabovestepstosetyourCSSforeitheroftheusageoptionsbelow.

Viadataattributes
Toeasilyaddaffixbehaviortoanyelement,justadd dataspy="affix"totheelementyouwantto
spyon.Useoffsetstodefinewhentotogglethepinningofanelement.
<divdataspy="affix"dataoffsettop="60"dataoffsetbottom="200">
...
</div>

ViaJavaScript
http://getbootstrap.com/javascript/

49/51

7/5/2016

JavaScript Bootstrap

CalltheaffixpluginviaJavaScript:
$('#myAffix').affix({
offset:{
top:100,
bottom:function(){
return(this.bottom=$('.footer').outerHeight(true))
}
}
})

Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionnameto
data,asin dataoffsettop="200".
Name

type

default

description

offset

number|
function|
object

10

Pixelstooffsetfromscreenwhencalculatingpositionof
scroll.Ifasinglenumberisprovided,theoffsetwillbe
appliedinbothtopandbottomdirections.Toprovidea
unique,bottomandtopoffsetjustprovideanobject
offset:{top:10}or offset:{top:10,
bottom:5}.Useafunctionwhenyouneedto
dynamicallycalculateanoffset.

target

selector|
node|
jQuery
element

the

Specifiesthetargetelementoftheaffix.

window

object

Methods
.affix(options)
Activatesyourcontentasaffixedcontent.Acceptsanoptionaloptions object.
$('#myAffix').affix({
offset:15
})

.affix('checkPosition')
Recalculatesthestateoftheaffixbasedonthedimensions,position,andscrollpositionoftherelevant
elements.The .affix, .affixtop,and .affixbottomclassesareaddedtoorremovedfromthe
affixedcontentaccordingtothenewstate.Thismethodneedstobecalledwheneverthedimensionsof
theaffixedcontentorthetargetelementarechanged,toensurecorrectpositioningoftheaffixed
content.

http://getbootstrap.com/javascript/

50/51

7/5/2016

JavaScript Bootstrap

$('#myAffix').affix('checkPosition')

Events
Bootstrap'saffixpluginexposesafeweventsforhookingintoaffixfunctionality.
EventType

Description

affix.bs.affix

Thiseventfiresimmediatelybeforetheelementhasbeenaffixed.

affixed.bs.affix

Thiseventisfiredaftertheelementhasbeenaffixed.

affixtop.bs.affix

Thiseventfiresimmediatelybeforetheelementhasbeenaffixedtop.

affixedtop.bs.affix

Thiseventisfiredaftertheelementhasbeenaffixedtop.

affixbottom.bs.affix

Thiseventfiresimmediatelybeforetheelementhasbeenaffixedbottom.

affixedbottom.bs.affix

Thiseventisfiredaftertheelementhasbeenaffixedbottom.

GitHub(https://github.com/twbs/bootstrap) Twitter(https://twitter.com/getbootstrap)
Examples(../gettingstarted/#examples) About(../about/)
Designedandbuiltwithalltheloveintheworldby@mdo(https://twitter.com/mdo)and@fat
(https://twitter.com/fat).Maintainedbythecoreteam(https://github.com/orgs/twbs/people)withthehelp
ofourcontributors(https://github.com/twbs/bootstrap/graphs/contributors).
CodelicensedMIT(https://github.com/twbs/bootstrap/blob/master/LICENSE),docsCCBY3.0
(https://creativecommons.org/licenses/by/3.0/).

http://getbootstrap.com/javascript/

51/51