You are on page 1of 42

28/6/2014 JavaScript Bootstrap

http://getbootstrap.com/javascript/ 1/42
JavaScript
BringBootstrap'scomponentstolifewithoveradozencustom
jQueryplugins.Easilyincludethemall,oronebyone.
(https://bs.serving
sys.com/BurstingPipe/adServer.bs?
cn=brd&FlightID=8817843&Page=&PluID=0&Pos=524119787)
SendGridSMTP
Service:
(https://bs.serving
sys.com/BurstingPipe/adServer.bs?
cn=brd&FlightID=8817843&Page=&PluID=0&Pos=524119787)
AvoidSpamFolders&
EnsureEmailDelivery.
FreeSignup.
adsviaCarbon
(http://carbonads.com)
Overview
Individualorcompiled
Pluginscanbeincludedindividually(usingBootstrap'sindividual *.js files),orallatonce(using
bootstrap.js ortheminified bootstrap.min.js ).
UsingthecompiledJavaScript
Both bootstrap.js and bootstrap.min.js containallpluginsinasinglefile.Includeonly
one.
Componentdataattributes
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 2/42
Don'tusedataattributesfrommultiplepluginsonthesameelement.Forexample,abutton
cannotbothhaveatooltipandtoggleamodal.Toaccomplishthis,useawrappingelement.
Plugindependencies
SomepluginsandCSScomponentsdependonotherplugins.Ifyouincludeplugins
individually,makesuretocheckforthesedependenciesinthedocs.Alsonotethatallplugins
dependonjQuery(thismeansjQuerymustbeincludedbeforethepluginfiles).Consultour
bower.json (https://github.com/twbs/bootstrap/blob/v3.2.0/bower.json)toseewhich
versionsofjQueryaresupported.
Dataattributes
YoucanuseallBootstrappluginspurelythroughthemarkupAPIwithoutwritingasinglelineof
JavaScript.ThisisBootstrap'sfirstclassAPIandshouldbeyourfirstconsiderationwhenusinga
plugin.
Thatsaid,insomesituationsitmaybedesirabletoturnthisfunctionalityoff.Therefore,wealso
providetheabilitytodisablethedataattributeAPIbyunbindingalleventsonthedocument
namespacedwith dataapi .Thislookslikethis:
$(document).off('.dataapi')
Alternatively,totargetaspecificplugin,justincludetheplugin'snameasanamespacealongwiththe
dataapinamespacelikethis:
$(document).off('.alert.dataapi')
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
Eachpluginalsoexposesitsrawconstructorona Constructor property:
$.fn.popover.Constructor .Ifyou'dliketogetaparticularplugininstance,retrieveitdirectlyfrom
anelement: $('[rel="popover"]').data('popover') .
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 3/42
Noconflict
SometimesitisnecessarytouseBootstrappluginswithotherUIframeworks.Inthesecircumstances,
namespacecollisionscanoccasionallyoccur.Ifthishappens,youmaycall .noConflict onthe
pluginyouwishtorevertthevalueof.
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 preventDefault functionality.Thisprovidestheabilitytostopthe
executionofanactionbeforeitstarts.
$('#myModal').on('show.bs.modal',function(e){
if(!data)returne.preventDefault()//stopsmodalfrombeingshown
})
Thirdpartylibraries
BootstrapdoesnotofficiallysupportthirdpartyJavaScriptlibrarieslikePrototypeor
jQueryUI.Despite .noConflict andnamespacedevents,theremaybecompatibility
problemsthatyouneedtofixonyourown.
Transitionstransition.js
Abouttransitions
Forsimpletransitioneffects,include transition.js oncealongsidetheotherJSfiles.Ifyou're
usingthecompiled(orminified) bootstrap.js ,thereisnoneedtoincludethisit'salreadythere.
What'sinside
Transition.jsisabasichelperfor transitionEnd eventsaswellasaCSStransitionemulator.It's
usedbytheotherpluginstocheckforCSStransitionsupportandtocatchhangingtransitions.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 4/42
Modalsmodal.js
Examples
Modalsarestreamlined,butflexible,dialogpromptswiththeminimumrequiredfunctionalityand
smartdefaults.
Overlappingmodalsnotsupported
Besurenottoopenamodalwhileanotherisstillvisible.Showingmorethanonemodalata
timerequirescustomcode.
Modalmarkupplacement
Alwaystrytoplaceamodal'sHTMLcodeinatoplevelpositioninyourdocumenttoavoid
othercomponentsaffectingthemodal'sappearanceand/orfunctionality.
Mobiledevicecaveats
Therearesomecaveatsregardingusingmodalsonmobiledevices.Seeourbrowsersupport
docs(../gettingstarted/#supportfixedpositionkeyboards)fordetails.
Staticexample
Arenderedmodalwithheader,body,andsetofactionsinthefooter.
EXAMPLE
Modaltitle
Close Savechanges

Onefinebody
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 5/42
<divclass="modalfade">
<divclass="modaldialog">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"><span
ariahidden="true">&times</span><spanclass="sronly">Close</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.Itwillslidedownandfadeinfromthetop
ofthepage.
Launchdemomodal
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 6/42
<!Buttontriggermodal>
<buttonclass="btnbtnprimarybtnlg"datatoggle="modal"data
target="#myModal">
Launchdemomodal
</button>
<!Modal>
<divclass="modalfade"id="myModal"tabindex="1"role="dialog"aria
labelledby="myModalLabel"ariahidden="true">
<divclass="modaldialog">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"><span
ariahidden="true">&times</span><spanclass="sronly">Close</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" to .modal , arialabelledby="myModalLabel" attribute
toreferencethemodaltitle,and ariahidden="true" totellassistivetechnologiestoskip
themodal'sDOMelements.
Additionally,youmaygiveadescriptionofyourmodaldialogwith ariadescribedby on
.modal .
EmbeddingYouTubevideos
EmbeddingYouTubevideosinmodalsrequiresadditionalJavaScriptnotinBootstrapto
automaticallystopplaybackandmore.SeethishelpfulStackOverflowpost
(http://stackoverflow.com/questions/18622508/bootstrap3andyoutubeinmodal)formore
information.
Optionalsizes
Modalshavetwooptionalsizes,availableviamodifierclassestobeplacedona .modaldialog .
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 7/42
<!Largemodal>
<buttonclass="btnbtnprimary"datatoggle="modal"datatarget=".bs
examplemodallg">Largemodal</button>
<divclass="modalfadebsexamplemodallg"tabindex="1"role="dialog"
arialabelledby="myLargeModalLabel"ariahidden="true">
<divclass="modaldialogmodallg">
<divclass="modalcontent">
...
</div>
</div>
</div>
<!Smallmodal>
<buttonclass="btnbtnprimary"datatoggle="modal"datatarget=".bs
examplemodalsm">Smallmodal</button>
<divclass="modalfadebsexamplemodalsm"tabindex="1"role="dialog"
arialabelledby="mySmallModalLabel"ariahidden="true">
<divclass="modaldialogmodalsm">
<divclass="modalcontent">
...
</div>
</div>
</div>
Removeanimation
Formodalsthatsimplyappearratherthanfadeintoview,removethe .fade classfromyourmodal
markup.
<divclass="modal"tabindex="1"role="dialog"arialabelledby=""aria
hidden="true">
...
</div>
Usage
Themodalplugintogglesyourhiddencontentondemand,viadataattributesorJavaScript.Italso
adds .modalopen tothe <body> tooverridedefaultscrollingbehaviorandgeneratesa .modal
backdrop toprovideaclickareafordismissingshownmodalswhenclickingoutsidethemodal.
Viadataattributes
Largemodal Smallmodal
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 8/42
ActivateamodalwithoutwritingJavaScript.Set datatoggle="modal" onacontrollerelement,like
abutton,alongwitha datatarget="#foo" or href="#foo" totargetaspecificmodaltotoggle.
<buttontype="button"datatoggle="modal"datatarget="#myModal">Launch
modal</button>
ViaJavaScript
Callamodalwithid myModal withasinglelineofJavaScript:
$('#myModal').modal(options)
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to data ,asin databackdrop="" .
Name type default description
backdrop booleanor
thestring
'static'
true Includesamodalbackdropelement.Alternatively,specify
static forabackdropwhichdoesn'tclosethemodalon
click.
keyboard boolean true Closesthemodalwhenescapekeyispressed
show boolean true Showsthemodalwheninitialized.
remote path false IfaremoteURLisprovided,contentwillbeloadedone
timeviajQuery's load methodandinjectedintothe
.modalcontent div.Ifyou'reusingthedataapi,you
mayalternativelyusethe href attributetospecifythe
remotesource.Anexampleofthisisshownbelow:
<adatatoggle="modal"
href="remote.html"data
target="#modal">Clickme</a>
Methods
.modal(options)
Activatesyourcontentasamodal.Acceptsanoptionaloptions object .
$('#myModal').modal({
keyboard:false
})
.modal('toggle')
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 9/42
Manuallytogglesamodal.Returnstothecallerbeforethemodalhasactuallybeenshownor
hidden(i.e.beforethe shown.bs.modal or hidden.bs.modal eventoccurs).
$('#myModal').modal('toggle')
.modal('show')
Manuallyopensamodal.Returnstothecallerbeforethemodalhasactuallybeenshown(i.e.
beforethe shown.bs.modal eventoccurs).
$('#myModal').modal('show')
.modal('hide')
Manuallyhidesamodal.Returnstothecallerbeforethemodalhasactuallybeenhidden(i.e.
beforethe hidden.bs.modal eventoccurs).
$('#myModal').modal('hide')
Events
Bootstrap'smodalclassexposesafeweventsforhookingintomodalfunctionality.
EventType Description
show.bs.modal Thiseventfiresimmediatelywhenthe show instancemethodiscalled.If
causedbyaclick,theclickedelementisavailableasthe relatedTarget
propertyoftheevent.
shown.bs.modal Thiseventisfiredwhenthemodalhasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).Ifcausedbyaclick,theclicked
elementisavailableasthe relatedTarget propertyoftheevent.
hide.bs.modal Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeen
called.
hidden.bs.modal Thiseventisfiredwhenthemodalhasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).
loaded.bs.modal Thiseventisfiredwhenthemodalhasloadedcontentusingtheremote
option.
$('#myModal').on('hidden.bs.modal',function(e){
//dosomething...
})
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 10/42
Dropdownsdropdown.js
Examples
Adddropdownmenustonearlyanythingwiththissimpleplugin,includingthenavbar,tabs,andpills.
Withinanavbar
Withinpills
Usage
ViadataattributesorJavaScript,thedropdownplugintoggleshiddencontent(dropdownmenus)by
togglingthe .open classontheparentlistitem.Whenopened,thepluginalsoadds .dropdown
backdrop asaclickareaforclosingdropdownmenuswhenclickingoutsidethemenu.Note:The
datatoggle=dropdown attributeisreliedonforclosingdropdownmenusatanapplicationlevel,
soit'sagoodideatoalwaysuseit.
Viadataattributes
Add datatoggle="dropdown" toalinkorbuttontotoggleadropdown.
<divclass="dropdown">
<adatatoggle="dropdown"href="#">Dropdowntrigger</a>
<ulclass="dropdownmenu"role="menu"arialabelledby="dLabel">
...
</ul>
</div>
TokeepURLsintact,usethe datatarget attributeinsteadof href="#" .
EXAMPLE
Regularlink Dropdown Dropdown2 Dropdown3
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 11/42
<divclass="dropdown">
<aid="dLabel"role="button"datatoggle="dropdown"datatarget="#"
href="/page.html">
Dropdown<spanclass="caret"></span>
</a>
<ulclass="dropdownmenu"role="menu"arialabelledby="dLabel">
...
</ul>
</div>
ViaJavaScript
CallthedropdownsviaJavaScript:
$('.dropdowntoggle').dropdown()
datatoggle="dropdown" stillrequired
RegardlessofwhetheryoucallyourdropdownviaJavaScriptorinsteadusethedataapi,
datatoggle="dropdown" isalwaysrequiredtobepresentonthedropdown'strigger
element.
Options
None
Methods
$().dropdown('toggle')
Togglesthedropdownmenuofagivennavbarortabbednavigation.
Events
Alldropdowneventsarefiredatthe .dropdownmenu 'sparentelement.
EventType Description
show.bs.dropdown Thiseventfiresimmediatelywhentheshowinstancemethodiscalled.The
togglinganchorelementisavailableasthe relatedTarget propertyof
theevent.
shown.bs.dropdown Thiseventisfiredwhenthedropdownhasbeenmadevisibletotheuser
(willwaitforCSStransitions,tocomplete).Thetogglinganchorelementis
availableasthe relatedTarget propertyoftheevent.
hide.bs.dropdown Thiseventisfiredimmediatelywhenthehideinstancemethodhasbeen
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 12/42
called.Thetogglinganchorelementisavailableasthe relatedTarget
propertyoftheevent.
hidden.bs.dropdown Thiseventisfiredwhenthedropdownhasfinishedbeinghiddenfromthe
user(willwaitforCSStransitions,tocomplete).Thetogglinganchor
elementisavailableasthe relatedTarget propertyoftheevent.
$('#myDropdown').on('show.bs.dropdown',function(){
//dosomething
})
ScrollSpyscrollspy.js
Exampleinnavbar
TheScrollSpypluginisforautomaticallyupdatingnavtargetsbasedonscrollposition.Scrollthearea
belowthenavbarandwatchtheactiveclasschange.Thedropdownsubitemswillbehighlightedas
well.
Usage
Requiresrelativepositioning
Nomattertheimplementationmethod,scrollspyrequirestheuseof position:relative onthe
elementyou'respyingon.Inmostcasesthisisthe <body> .
Viadataattributes
@fat
Adleggingskeytar,brunchidartpartydolorlabore.Pitchforkyrenimlofibeforetheysoldoutqui.
Tumblrfarmtotablebicyclerightswhatever.Animkeffiyehcarlescardigan.Velitseitan
mcsweeney'sphotobooth3wolfmoonirure.Cosbysweaterlomojeanshorts,williamsburghoodie
minimquiyouprobablyhaven'theardofthemetcardigantrustfundculpabiodieselwesanderson
aesthetic.Nihiltattooedaccusamus,credironybiodieselkeffiyehartisanullamcoconsequat.
@mdo
Veniammarfamustacheskateboard,adipisicingfugiatvelitpitchforkbeard.Freeganbeardaliqua
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 13/42
Toeasilyaddscrollspybehaviortoyourtopbarnavigation,add dataspy="scroll" totheelement
youwanttospyon(mosttypicallythiswouldbethe <body> ).Thenaddthe datatarget attribute
withtheIDorclassoftheparentelementofanyBootstrap .nav component.
body{
position:relative
}
<bodydataspy="scroll"datatarget=".navbarexample">
...
<divclass="navbarexample">
<ulclass="navnavtabs"role="tablist">
...
</ul>
</div>
...
</body>
ViaJavaScript
Afteradding position:relative inyourCSS,callthescrollspyviaJavaScript:
$('body').scrollspy({target:'.navbarexample'})
ResolvableIDtargetsrequired
Navbarlinksmusthaveresolvableidtargets.Forexample,a <ahref="#home">home</a>
mustcorrespondtosomethingintheDOMlike <divid="home"></div> .
Non :visible targetelementsignored
Targetelementsthatarenot :visible accordingtojQuery(http://api.jquery.com/visible
selector/)willbeignoredandtheircorrespondingnavitemswillneverbehighlighted.
Methods
.scrollspy('refresh')
WhenusingscrollspyinconjunctionwithaddingorremovingofelementsfromtheDOM,you'llneed
tocalltherefreshmethodlikeso:
$('[dataspy="scroll"]').each(function(){
var$spy=$(this).scrollspy('refresh')
})
Options
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 14/42
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to data ,asin dataoffset="" .
Name type default description
offset number 10 Pixelstooffsetfromtopwhencalculatingpositionof
scroll.
Events
EventType Description
activate.bs.scrollspy Thiseventfireswheneveranewitembecomesactivatedbythescrollspy.
$('#myScrollspy').on('activate.bs.scrollspy',function(){
//dosomething
})
Togglabletabstab.js
Exampletabs
Addquick,dynamictabfunctionalitytotransitionthroughpanesoflocalcontent,evenviadropdown
menus.
Extendstabbednavigation
Thispluginextendsthetabbednavigationcomponent(../components/#navtabs)toadd
tabbableareas.
Rawdenimyouprobablyhaven'theardofthemjeanshortsAustin.Nesciunttofustumptownaliqua,
retrosynthmastercleanse.Mustacheclichetempor,williamsburgcarlesveganhelvetica.
Reprehenderitbutcherretrokeffiyehdreamcatchersynth.Cosbysweatereubanhmi,quiirureterry
richardsonexsquid.Aliquipplaceatsalviacillumiphone.Seitanaliquipquiscardiganamerican
apparel,butchervoluptatenisiqui.
Home Profile Dropdown
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 15/42
Usage
EnabletabbabletabsviaJavaScript(eachtabneedstobeactivatedindividually):
$('#myTaba').click(function(e){
e.preventDefault()
$(this).tab('show')
})
Youcanactivateindividualtabsinseveralways:
$('#myTaba[href="#profile"]').tab('show')//Selecttabbyname
$('#myTaba:first').tab('show')//Selectfirsttab
$('#myTaba:last').tab('show')//Selectlasttab
$('#myTabli:eq(2)a').tab('show')//Selectthirdtab(0indexed)
Markup
YoucanactivateataborpillnavigationwithoutwritinganyJavaScriptbysimplyspecifying data
toggle="tab" or datatoggle="pill" onanelement.Addingthe nav and navtabs classes
tothetab ul willapplytheBootstraptabstyling(../components/#navtabs),whileaddingthe nav
and navpills classeswillapplypillstyling(../components/#navpills).
<!Navtabs>
<ulclass="navnavtabs"role="tablist">
<liclass="active"><ahref="#home"role="tab"data
toggle="tab">Home</a></li>
<li><ahref="#profile"role="tab"datatoggle="tab">Profile</a></li>
<li><ahref="#messages"role="tab"datatoggle="tab">Messages</a>
</li>
<li><ahref="#settings"role="tab"datatoggle="tab">Settings</a>
</li>
</ul>
<!Tabpanes>
<divclass="tabcontent">
<divclass="tabpaneactive"id="home">...</div>
<divclass="tabpane"id="profile">...</div>
<divclass="tabpane"id="messages">...</div>
<divclass="tabpane"id="settings">...</div>
</div>
Fadeeffect
Tomaketabsfadein,add .fade toeach .tabpane .Thefirsttabpanemustalsohave .in to
properlyfadeininitialcontent.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 16/42
<divclass="tabcontent">
<divclass="tabpanefadeinactive"id="home">...</div>
<divclass="tabpanefade"id="profile">...</div>
<divclass="tabpanefade"id="messages">...</div>
<divclass="tabpanefade"id="settings">...</div>
</div>
Methods
$().tab
Activatesatabelementandcontentcontainer.Tabshouldhaveeithera datatarget oran href
targetingacontainernodeintheDOM.
<ulclass="navnavtabs"role="tablist"id="myTab">
<liclass="active"><ahref="#home"role="tab"data
toggle="tab">Home</a></li>
<li><ahref="#profile"role="tab"datatoggle="tab">Profile</a></li>
<li><ahref="#messages"role="tab"datatoggle="tab">Messages</a>
</li>
<li><ahref="#settings"role="tab"datatoggle="tab">Settings</a>
</li>
</ul>
<divclass="tabcontent">
<divclass="tabpaneactive"id="home">...</div>
<divclass="tabpane"id="profile">...</div>
<divclass="tabpane"id="messages">...</div>
<divclass="tabpane"id="settings">...</div>
</div>
<script>
$(function(){
$('#myTaba:last').tab('show')
})
</script>
Events
EventType Description
show.bs.tab Thiseventfiresontabshow,butbeforethenewtabhasbeenshown.Use
event.target and event.relatedTarget totargettheactivetaband
thepreviousactivetab(ifavailable)respectively.
shown.bs.tab Thiseventfiresontabshowafteratabhasbeenshown.Use
event.target and event.relatedTarget totargettheactivetaband
thepreviousactivetab(ifavailable)respectively.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 17/42
$('a[datatoggle="tab"]').on('shown.bs.tab',function(e){
e.target//activatedtab
e.relatedTarget//previoustab
})
Tooltipstooltip.js
Examples
InspiredbytheexcellentjQuery.tipsypluginwrittenbyJasonFrameTooltipsareanupdatedversion,
whichdon'trelyonimages,useCSS3foranimations,anddataattributesforlocaltitlestorage.
Hoveroverthelinksbelowtoseetooltips:
Fourdirections
<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>
Tightpantsnextlevelkeffiyehyouprobablyhaven'theardofthem.Photoboothbeardrawdenim
letterpressveganmessengerbagstumptown.Farmtotableseitan,mcsweeney'sfixiesustainable
quinoa8bitamericanapparelhaveaterryrichardsonvinylchambray.Beardstumptown,cardigans
banhmilomothundercats.Tofubiodieselwilliamsburgmarfa,fourlokomcsweeney'scleansevegan
chambray.Areallyironicartisanwhateverkeytar,scenesterfarmtotablebanksyAustintwitter
handlefreegancredrawdenimsingleorigincoffeeviral.
EXAMPLE
Tooltiponleft Tooltipontop Tooltiponbottom Tooltiponright
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 18/42
Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumust
initializethemyourself.
Tooltipsinbuttongroupsandinputgroupsrequirespecialsetting
Whenusingtooltipsonelementswithina .btngroup oran .inputgroup ,you'llhaveto
specifytheoption container:'body' (documentedbelow)toavoidunwantedsideeffects
(suchastheelementgrowingwiderand/orlosingitsroundedcornerswhenthetooltipis
triggered).
Don'ttrytoshowtooltipsonhiddenelements
Invoking $(...).tooltip('show') whenthetargetelementis display:none will
causethetooltiptobeincorrectlypositioned.
Tooltipsondisabledelementsrequirewrapperelements
Toaddatooltiptoa disabled or .disabled element,puttheelementinsideofa <div>
andapplythetooltiptothat <div> instead.
Usage
Thetooltipplugingeneratescontentandmarkupondemand,andbydefaultplacestooltipsaftertheir
triggerelement.
TriggerthetooltipviaJavaScript:
$('#example').tooltip(options)
Markup
Therequiredmarkupforatooltipisonlya data attributeand title ontheHTMLelementyou
wishtohaveatooltip.Thegeneratedmarkupofatooltipisrathersimple,thoughitdoesrequirea
position(bydefault,setto top bytheplugin).
Multiplelinelinks
Sometimesyouwanttoaddatooltiptoahyperlinkthatwrapsmultiplelines.Thedefault
behaviorofthetooltippluginistocenterithorizontallyandvertically.Add whitespace:
nowrap toyouranchorstoavoidthis.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 19/42
1<!HTMLtowrite>
2<ahref="#"datatoggle="tooltip"title="Sometooltiptext!">Hover
overme</a>
3
4<!Generatedmarkupbytheplugin>
5<divclass="tooltiptop"role="tooltip">
6<divclass="tooltiparrow"></div>
7<divclass="tooltipinner">
8Sometooltiptext!
9</div>
10</div>
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to 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
0 Delayshowingandhidingthetooltip(ms)
doesnotapplytomanualtriggertype
Ifanumberissupplied,delayisappliedtoboth
hide/show
Objectstructureis: delay:{show:500,
hide:100}
html boolean false InsertHTMLintothetooltip.Iffalse,jQuery's
text methodwillbeusedtoinsertcontent
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.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 20/42
selector string false Ifaselectorisprovided,tooltipobjectswillbe
delegatedtothespecifiedtargets.Inpractice,
thisisusedtoenabledynamicHTMLcontent
tohavetooltipsadded.Seethis
(https://github.com/twbs/bootstrap/issues/4215)
andaninformativeexample
(http://jsfiddle.net/fScua/).
template string '<div
class="tooltip"
role="tooltip">
<div
class="tooltip
arrow"></div>
<div
class="tooltip
inner"></div>
</div>'
BaseHTMLtousewhencreatingthetooltip.
Thetooltip's title willbeinjectedintothe
.tooltipinner .
.tooltiparrow willbecomethetooltip's
arrow.
Theoutermostwrapperelementshouldhave
the .tooltip class.
title string|
function
'' Defaulttitlevalueif title attributeisn't
present
trigger string 'hoverfocus' Howtooltipistriggeredclick|hover|focus|
manual.Youmaypassmultipletriggers
separatethemwithaspace.
viewport string|
object
{selector:'body',
padding:0}
Keepsthetooltipwithintheboundsofthis
element.Example: viewport:'#viewport'
or {selector:'#viewport',padding:
0}
Dataattributesforindividualtooltips
Optionsforindividualtooltipscanalternativelybespecifiedthroughtheuseofdataattributes,
asexplainedabove.
Methods
$().tooltip(options)
Attachesatooltiphandlertoanelementcollection.
.tooltip('show')
Revealsanelement'stooltip.
$('#element').tooltip('show')
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 21/42
.tooltip('hide')
Hidesanelement'stooltip.
$('#element').tooltip('hide')
.tooltip('toggle')
Togglesanelement'stooltip.
$('#element').tooltip('toggle')
.tooltip('destroy')
Hidesanddestroysanelement'stooltip.
$('#element').tooltip('destroy')
Events
EventType Description
show.bs.tooltip Thiseventfiresimmediatelywhenthe show instancemethodiscalled.
shown.bs.tooltip Thiseventisfiredwhenthetooltiphasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).
hide.bs.tooltip Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeen
called.
hidden.bs.tooltip Thiseventisfiredwhenthetooltiphasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).
$('#myTooltip').on('hidden.bs.tooltip',function(){
//dosomething
})
Popoverspopover.js
Examples
Addsmalloverlaysofcontent,likethoseontheiPad,toanyelementforhousingsecondary
information.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 22/42
Plugindependency
PopoversrequirethetooltipplugintobeincludedinyourversionofBootstrap.
Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumust
initializethemyourself.
Popoversinbuttongroupsandinputgroupsrequirespecialsetting
Whenusingpopoversonelementswithina .btngroup oran .inputgroup ,you'llhave
tospecifytheoption container:'body' (documentedbelow)toavoidunwantedside
effects(suchastheelementgrowingwiderand/orlosingitsroundedcornerswhenthe
popoveristriggered).
Don'ttrytoshowpopoversonhiddenelements
Invoking $(...).popover('show') whenthetargetelementis display:none will
causethepopovertobeincorrectlypositioned.
Popoversondisabledelementsrequirewrapperelements
Toaddapopovertoa disabled or .disabled element,puttheelementinsideofa
<div> andapplythepopovertothat <div> instead.
Staticpopover
Fouroptionsareavailable:top,right,bottom,andleftaligned.
EXAMPLE
Popovertop
Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Popoverright
Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Popoverbottom Popoverleft
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 23/42
Livedemo
<buttontype="button"class="btnbtnlgbtndanger"datatoggle="popover"
title="Popovertitle"datacontent="Andhere'ssomeamazingcontent.It's
veryengaging.Right?">Clicktotogglepopover</button>
Fourdirections
<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="Vivamussagittis
lacusvelauguelaoreetrutrumfaucibus.">
Popoveronright
</button>
Clicktotogglepopover
EXAMPLE
Popoveronleft Popoverontop Popoveronbottom Popoveronright
EXAMPLE
Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 24/42
Dismissonnextclick
Usethe focus triggertodismisspopoversonthenextclickthattheusermakes.
<buttontype="button"class="btnbtnlgbtndangerpopoverdismiss"data
toggle="popover"title="Dismissiblepopover"datacontent="Andhere'ssome
amazingcontent.It'sveryengaging.Right?">Dismissiblepopover</button>
$('.popoverdismiss').popover({
trigger:'focus'
})
Multiplelinelinks
Sometimesyouwanttoaddapopovertoahyperlinkthatwrapsmultiplelines.Thedefault
behaviorofthepopoverpluginistocenterithorizontallyandvertically.Add whitespace:
nowrap toyouranchorstoavoidthis.
Usage
EnablepopoversviaJavaScript:
$('#example').popover(options)
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to data ,asin dataanimation="" .
Name Type Default Description
animation boolean true ApplyaCSSfadetransitiontothepopover
container string|
false
false Appendsthepopovertoaspecificelement.
Example: container:'body' .Thisoptionis
particularlyusefulinthatitallowsyouto
positionthepopoverintheflowofthe
documentnearthetriggeringelementwhich
Dismissiblepopover
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 25/42
willpreventthepopoverfromfloatingaway
fromthetriggeringelementduringawindow
resize.
content string|
function
'' Defaultcontentvalueif datacontent
attributeisn'tpresent.
Ifafunctionisgiven,itwillbecalledwith1
argument,whichistheelementthatthe
popoverisattachedto.
delay number|
object
0 Delayshowingandhidingthepopover(ms)
doesnotapplytomanualtriggertype
Ifanumberissupplied,delayisappliedtoboth
hide/show
Objectstructureis: delay:{show:500,
hide:100}
html boolean false InsertHTMLintothepopover.Iffalse,jQuery's
text methodwillbeusedtoinsertcontent
intotheDOM.Usetextifyou'reworriedabout
XSSattacks.
placement string|
function
'right' Howtopositionthepopovertop|bottom|left
|right|auto.
When"auto"isspecified,itwilldynamically
reorientthepopover.Forexample,if
placementis"autoleft",thepopoverwilldisplay
totheleftwhenpossible,otherwiseitwill
displayright.
selector string false Ifaselectorisprovided,popoverobjectswillbe
delegatedtothespecifiedtargets.Inpractice,
thisisusedtoenabledynamicHTMLcontent
tohavepopoversadded.Seethis
(https://github.com/twbs/bootstrap/issues/4215)
andaninformativeexample
(http://jsfiddle.net/fScua/).
template string '<div
class="popover"
role="tooltip">
<div
class="arrow">
BaseHTMLtousewhencreatingthepopover.
Thepopover's title willbeinjectedintothe
.popovertitle .
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 26/42
</div><h3
class="popover
title"></h3>
<div
class="popover
content"></div>
</div>'
Thepopover's content willbeinjectedinto
the .popovercontent .
.arrow willbecomethepopover'sarrow.
Theoutermostwrapperelementshouldhave
the .popover class.
title string|
function
'' Defaulttitlevalueif title attributeisn't
present
trigger string 'click' Howpopoveristriggeredclick|hover|focus
|manual.Youmaypassmultipletriggers
separatethemwithaspace.
viewport string|
object
{selector:'body',
padding:0}
Keepsthepopoverwithintheboundsofthis
element.Example: viewport:'#viewport'
or {selector:'#viewport',padding:
0}
Dataattributesforindividualpopovers
Optionsforindividualpopoverscanalternativelybespecifiedthroughtheuseofdata
attributes,asexplainedabove.
Methods
$().popover(options)
Initializespopoversforanelementcollection.
.popover('show')
Revealsanelementspopover.
$('#element').popover('show')
.popover('hide')
Hidesanelementspopover.
$('#element').popover('hide')
.popover('toggle')
Togglesanelementspopover.
$('#element').popover('toggle')
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 27/42
.popover('destroy')
Hidesanddestroysanelement'spopover.
$('#element').popover('destroy')
Events
EventType Description
show.bs.popover Thiseventfiresimmediatelywhenthe show instancemethodiscalled.
shown.bs.popover Thiseventisfiredwhenthepopoverhasbeenmadevisibletotheuser
(willwaitforCSStransitionstocomplete).
hide.bs.popover Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeen
called.
hidden.bs.popover Thiseventisfiredwhenthepopoverhasfinishedbeinghiddenfromthe
user(willwaitforCSStransitionstocomplete).
$('#myPopover').on('hidden.bs.popover',function(){
//dosomething
})
Alertmessagesalert.js
Examplealerts
Adddismissfunctionalitytoallalertmessageswiththisplugin.
Holyguacamole!Bestcheckyoself,you'renotlookingtoogood.

EXAMPLE
Ohsnap!Yougotanerror!

EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 28/42
Usage
EnabledismissalofanalertviaJavaScript:
$(".alert").alert()
Markup
Justadd datadismiss="alert" toyourclosebuttontoautomaticallygiveanalertclose
functionality.
<buttontype="button"class="close"datadismiss="alert"><spanaria
hidden="true">&times</span><spanclass="sronly">Close</span></button>
Methods
$().alert()
Wrapsallalertswithclosefunctionality.Tohaveyouralertsanimateoutwhenclosed,makesurethey
havethe .fade and .in classalreadyappliedtothem.
.alert('close')
Closesanalert.
$(".alert").alert('close')
Events
Bootstrap'salertclassexposesafeweventsforhookingintoalertfunctionality.
EventType Description
close.bs.alert Thiseventfiresimmediatelywhenthe close instancemethodiscalled.
closed.bs.alert Thiseventisfiredwhenthealerthasbeenclosed(willwaitforCSS
transitionstocomplete).
$('#myalert').on('closed.bs.alert',function(){
//dosomething
})
Changethisandthatandtryagain.Duismollis,estnoncommodoluctus,nisieratporttitorligula,
egetlaciniaodiosemnecelit.Crasmattisconsecteturpurussitametfermentum.
Takethisaction Ordothis
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 29/42
Buttonsbutton.js
Exampleuses
Domorewithbuttons.Controlbuttonstatesorcreategroupsofbuttonsformorecomponentslike
toolbars.
Stateful
Add dataloadingtext="Loading..." tousealoadingstateonabutton.
<buttontype="button"id="loadingexamplebtn"dataloading
text="Loading..."class="btnbtnprimary">
Loadingstate
</button>
<script>
$('#loadingexamplebtn').click(function(){
varbtn=$(this)
btn.button('loading')
$.ajax(...).always(function(){
btn.button('reset')
})
})
</script>
Singletoggle
Add datatoggle="button" toactivatetogglingonasinglebutton.
<buttontype="button"class="btnbtnprimary"datatoggle="button">Single
toggle</button>
Checkbox
Add datatoggle="buttons" toagroupofcheckboxesforcheckboxstyletogglingonbtngroup.
Loadingstate
EXAMPLE
Singletoggle
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 30/42
Precheckedoptionsneed .active
Forprecheckedoptions,youmustaddthe .active classtotheinput's label yourself.
<divclass="btngroup"datatoggle="buttons">
<labelclass="btnbtnprimaryactive">
<inputtype="checkbox"checked>Option1(prechecked)
</label>
<labelclass="btnbtnprimary">
<inputtype="checkbox">Option2
</label>
<labelclass="btnbtnprimary">
<inputtype="checkbox">Option3
</label>
</div>
Radio
Add datatoggle="buttons" toagroupofradioinputsforradiostyletogglingonbtngroup.
Preselectedoptionsneed .active
Forpreselectedoptions,youmustaddthe .active classtotheinput's label yourself.
<divclass="btngroup"datatoggle="buttons">
<labelclass="btnbtnprimaryactive">
<inputtype="radio"name="options"id="option1"checked>Option1
(preselected)
</label>
<labelclass="btnbtnprimary">
<inputtype="radio"name="options"id="option2">Option2
</label>
<labelclass="btnbtnprimary">
<inputtype="radio"name="options"id="option3">Option3
</label>
</div>
Option2 Option3
EXAMPLE
Option2 Option3
EXAMPLE
Option1(prechecked)
Option1(preselected)
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 31/42
Usage
EnablebuttonsviaJavaScript:
$('.btn').button()
Markup
Dataattributesareintegraltothebuttonplugin.Checkouttheexamplecodebelowforthevarious
markuptypes.
Options
None
Methods
$().button('toggle')
Togglespushstate.Givesthebuttontheappearancethatithasbeenactivated.
Autotoggling
Youcanenableautotogglingofabuttonbyusingthe datatoggle attribute.
<buttontype="button"class="btnbtnprimary"datatoggle="button">...
</button>
$().button('loading')
Setsbuttonstatetoloadingdisablesbuttonandswapstexttoloadingtext.Loadingtextshouldbe
definedonthebuttonelementusingthedataattribute dataloadingtext .
<buttonid="loadingexamplebtn"type="button"class="btnbtnprimary"
dataloadingtext="loadingstuff...">...</button>
<script>
$('#loadingexamplebtn').click(function(){
varbtn=$(this)
btn.button('loading')
$.ajax(...).always(function(){
btn.button('reset')
})
})
</script>
Crossbrowsercompatibility
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 32/42
Firefoxpersistsformcontrolstatesacrosspageloads
(https://github.com/twbs/bootstrap/issues/793).Aworkaroundforthisistouse
autocomplete="off" .
$().button('reset')
Resetsbuttonstateswapstexttooriginaltext.
$().button(string)
Resetsbuttonstateswapstexttoanydatadefinedtextstate.
<buttontype="button"class="btnbtnprimary"datacomplete
text="finished!">...</button>
<script>
$('.btn').button('complete')
</script>
Collapsecollapse.js
About
Getbasestylesandflexiblesupportforcollapsiblecomponentslikeaccordionsandnavigation.
Plugindependency
CollapserequiresthetransitionsplugintobeincludedinyourversionofBootstrap.
Exampleaccordion
Usingthecollapseplugin,webuiltasimpleaccordionbyextendingthepanelcomponent.
CollapsibleGroupItem#1
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamusterryrichardsonadsquid.
3wolfmoonofficiaaute,noncupidatatskateboarddolorbrunch.Foodtruckquinoanesciunt
laborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigin
coffeenullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeerlaborewes
andersoncrednesciuntsapienteeaproident.Adveganexcepteurbutchervicelomo.Leggings
occaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven't
heardofthemaccusamuslaboresustainableVHS.
EXAMPLE
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 33/42
<divclass="panelgroup"id="accordion">
<divclass="panelpaneldefault">
<divclass="panelheading">
<h4class="paneltitle">
<adatatoggle="collapse"dataparent="#accordion"
href="#collapseOne">
CollapsibleGroupItem#1
</a>
</h4>
</div>
<divid="collapseOne"class="panelcollapsecollapsein">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlife
accusamusterryrichardsonadsquid.3wolfmoonofficiaaute,non
cupidatatskateboarddolorbrunch.Foodtruckquinoanesciuntlaborum
eiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquid
singleorigincoffeenullaassumendashoreditchet.Nihilanimkeffiyeh
helvetica,craftbeerlaborewesandersoncrednesciuntsapienteea
proident.Adveganexcepteurbutchervicelomo.Leggingsoccaecatcraft
beerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven't
heardofthemaccusamuslaboresustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading">
<h4class="paneltitle">
<adatatoggle="collapse"dataparent="#accordion"
href="#collapseTwo">
CollapsibleGroupItem#2
</a>
</h4>
</div>
<divid="collapseTwo"class="panelcollapsecollapse">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlife
accusamusterryrichardsonadsquid.3wolfmoonofficiaaute,non
cupidatatskateboarddolorbrunch.Foodtruckquinoanesciuntlaborum
eiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquid
singleorigincoffeenullaassumendashoreditchet.Nihilanimkeffiyeh
helvetica,craftbeerlaborewesandersoncrednesciuntsapienteea
proident.Adveganexcepteurbutchervicelomo.Leggingsoccaecatcraft
beerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven't
heardofthemaccusamuslaboresustainableVHS.
</div>
</div>
</div>
CollapsibleGroupItem#2
CollapsibleGroupItem#3
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 34/42
</div>
<divclass="panelpaneldefault">
<divclass="panelheading">
<h4class="paneltitle">
<adatatoggle="collapse"dataparent="#accordion"
href="#collapseThree">
CollapsibleGroupItem#3
</a>
</h4>
</div>
<divid="collapseThree"class="panelcollapsecollapse">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlife
accusamusterryrichardsonadsquid.3wolfmoonofficiaaute,non
cupidatatskateboarddolorbrunch.Foodtruckquinoanesciuntlaborum
eiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquid
singleorigincoffeenullaassumendashoreditchet.Nihilanimkeffiyeh
helvetica,craftbeerlaborewesandersoncrednesciuntsapienteea
proident.Adveganexcepteurbutchervicelomo.Leggingsoccaecatcraft
beerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven't
heardofthemaccusamuslaboresustainableVHS.
</div>
</div>
</div>
</div>
Youcanalsousethepluginwithouttheaccordionmarkup.Makeabuttontoggletheexpandingand
collapsingofanotherelement.
<buttontype="button"class="btnbtndanger"datatoggle="collapse"
datatarget="#demo">
simplecollapsible
</button>
<divid="demo"class="collapsein">...</div>
Usage
Thecollapsepluginutilizesafewclassestohandletheheavylifting:
.collapse hidesthecontent
.collapse.in showsthecontent
.collapsing isaddedwhenthetransitionstarts,andremovedwhenitfinishes
Theseclassescanbefoundin componentanimations.less .
Viadataattributes
Justadd datatoggle="collapse" anda datatarget toelementtoautomaticallyassign
controlofacollapsibleelement.The datatarget attributeacceptsaCSSselectortoapplythe
collapseto.Besuretoaddtheclass collapse tothecollapsibleelement.Ifyou'dlikeittodefault
open,addtheadditionalclass in .
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 35/42
Toaddaccordionlikegroupmanagementtoacollapsiblecontrol,addthedataattribute data
parent="#selector" .Refertothedemotoseethisinaction.
ViaJavaScript
Enablemanuallywith:
$('.collapse').collapse()
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to data ,asin dataparent="" .
Name type default description
parent selector false Ifselectorthenallcollapsibleelementsunderthespecified
parentwillbeclosedwhenthiscollapsibleitemisshown.
(similartotraditionalaccordionbehaviorthisdependenton
the panel class)
toggle boolean true Togglesthecollapsibleelementoninvocation
Methods
.collapse(options)
Activatesyourcontentasacollapsibleelement.Acceptsanoptionaloptions object .
$('#myCollapsible').collapse({
toggle:false
})
.collapse('toggle')
Togglesacollapsibleelementtoshownorhidden.
.collapse('show')
Showsacollapsibleelement.
.collapse('hide')
Hidesacollapsibleelement.
Events
Bootstrap'scollapseclassexposesafeweventsforhookingintocollapsefunctionality.
EventType Description
show.bs.collapse Thiseventfiresimmediatelywhenthe show instancemethodiscalled.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 36/42
shown.bs.collapse Thiseventisfiredwhenacollapseelementhasbeenmadevisibletothe
user(willwaitforCSStransitionstocomplete).
hide.bs.collapse Thiseventisfiredimmediatelywhenthe hide methodhasbeencalled.
hidden.bs.collapse Thiseventisfiredwhenacollapseelementhasbeenhiddenfromtheuser
(willwaitforCSStransitionstocomplete).
$('#myCollapsible').on('hidden.bs.collapse',function(){
//dosomething
})
Carouselcarousel.js
Examples
Theslideshowbelowshowsagenericpluginandcomponentforcyclingthroughelementslikea
carousel.
Thirdslide

EXAMPLE

28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 37/42
<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">
<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"></span>
</a>
<aclass="rightcarouselcontrol"href="#carouselexamplegeneric"
role="button"dataslide="next">
<spanclass="glyphiconglyphiconchevronright"></span>
</a>
</div>
TransitionanimationsnotsupportedinInternetExplorer8&9
BootstrapexclusivelyusesCSS3foritsanimations,butInternetExplorer8&9don'tsupport
thenecessaryCSSproperties.Thus,therearenoslidetransitionanimationswhenusing
thesebrowsers.WehaveintentionallydecidednottoincludejQuerybasedfallbacksforthe
transitions.
Optionalcaptions
Addcaptionstoyourslideseasilywiththe .carouselcaption elementwithinany .item .Place
justaboutanyoptionalHTMLwithinthereanditwillbeautomaticallyalignedandformatted.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 38/42
<divclass="item">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
<h3>...</h3>
<p>...</p>
</div>
</div>
Accessibilityissue
Thecarouselcomponentisgenerallynotcompliantwithaccessibilitystandards.Ifyouneedto
becompliant,pleaseconsiderotheroptionsforpresentingyourcontent.
Usage
Multiplecarousels
Carouselsrequiretheuseofan id ontheoutermostcontainer(the .carousel )forcarousel
controlstofunctionproperly.Whenaddingmultiplecarousels,orwhenchangingacarousel's id ,be
suretoupdatetherelevantcontrols.
Viadataattributes
Usedataattributestoeasilycontrolthepositionofthecarousel. dataslide acceptsthekeywords
prev or next ,whichalterstheslidepositionrelativetoitscurrentposition.Alternatively,use
dataslideto topassarawslideindextothecarousel dataslideto="2" ,whichshiftsthe
slidepositiontoaparticularindexbeginningwith 0 .
900x500

EXAMPLE
Thirdslidelabel
Praesentcommodocursusmagna,velscelerisquenislconsectetur.

28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 39/42
The dataride="carousel" attributeisusedtomarkacarouselasanimatingstartingatpage
load.
ViaJavaScript
Callcarouselmanuallywith:
$('.carousel').carousel()
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to data ,asin datainterval="" .
Name type default description
interval number 5000 Theamountoftimetodelaybetweenautomaticallycyclingan
item.Iffalse,carouselwillnotautomaticallycycle.
pause string "hover" Pausesthecyclingofthecarouselonmouseenterand
resumesthecyclingofthecarouselonmouseleave.
wrap boolean true Whetherthecarouselshouldcyclecontinuouslyorhavehard
stops.
Methods
.carousel(options)
Initializesthecarouselwithanoptionaloptions object andstartscyclingthroughitems.
$('.carousel').carousel({
interval:2000
})
.carousel('cycle')
Cyclesthroughthecarouselitemsfromlefttoright.
.carousel('pause')
Stopsthecarouselfromcyclingthroughitems.
.carousel(number)
Cyclesthecarouseltoaparticularframe(0based,similartoanarray).
.carousel('prev')
Cyclestothepreviousitem.
.carousel('next')
Cyclestothenextitem.
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 40/42
Events
Bootstrap'scarouselclassexposestwoeventsforhookingintocarouselfunctionality.
Botheventshavethefollowingadditionalproperties:
direction :Thedirectioninwhichthecarouselissliding(either "left" or "right" ).
relatedTarget :TheDOMelementthatisbeingslidintoplaceastheactiveitem.
EventType Description
slide.bs.carousel Thiseventfiresimmediatelywhenthe slide instancemethodisinvoked.
slid.bs.carousel Thiseventisfiredwhenthecarouselhascompleteditsslidetransition.
$('#myCarousel').on('slide.bs.carousel',function(){
//dosomething
})
Affixaffix.js
Example
Thesubnavigationontherightisalivedemooftheaffixplugin.
Usage
UsetheaffixpluginviadataattributesormanuallywithyourownJavaScript.Inbothsituations,you
mustprovideCSSforthepositioningandwidthofyouraffixedcontent.
PositioningviaCSS
Theaffixplugintogglesbetweenthreeclasses,eachrepresentingaparticularstate: .affix ,
.affixtop ,and .affixbottom .Youmustprovidethestylesfortheseclassesyourself
(independentofthisplugin)tohandletheactualpositions.
Here'showtheaffixpluginworks:
1. Tostart,thepluginadds .affixtop toindicatetheelementisinitstopmostposition.Atthis
pointnoCSSpositioningisrequired.
2. Scrollingpasttheelementyouwantaffixedshouldtriggertheactualaffixing.Thisiswhere
.affix replaces .affixtop andsets position:fixed (providedbyBootstrap'scode
CSS).
3. Ifabottomoffsetisdefined,scrollingpastthatshouldreplace .affix with .affixbottom .
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 41/42
Sinceoffsetsareoptional,settingonerequiresyoutosettheappropriateCSS.Inthiscase,
add position:absolute whennecessary.ThepluginusesthedataattributeorJavaScript
optiontodeterminewheretopositiontheelementfromthere.
FollowtheabovestepstosetyourCSSforeitheroftheusageoptionsbelow.
Viadataattributes
Toeasilyaddaffixbehaviortoanyelement,justadd dataspy="affix" totheelementyouwantto
spyon.Useoffsetstodefinewhentotogglethepinningofanelement.
<divdataspy="affix"dataoffsettop="60"dataoffsetbottom="200">
...
</div>
ViaJavaScript
CalltheaffixpluginviaJavaScript:
$('#myaffix').affix({
offset:{
top:100
,bottom:function(){
return(this.bottom=$('.footer').outerHeight(true))
}
}
})
Options
OptionscanbepassedviadataattributesorJavaScript.Fordataattributes,appendtheoptionname
to 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
window
object
Specifiesthetargetelementoftheaffix.
Events
28/6/2014 JavaScript Bootstrap
http://getbootstrap.com/javascript/ 42/42
Star 69,178

Fork 25,440

Follow@twbootstrap 177Kfollowers

Tweet 4,685
Designedandbuiltwithalltheloveintheworldby@mdo(http://twitter.com/mdo)and@fat
(http://twitter.com/fat).
Maintainedbythecoreteam(https://github.com/twbs?tab=members)withthehelpofourcontributors
(https://github.com/twbs/bootstrap/graphs/contributors).
CodelicensedunderMIT(https://github.com/twbs/bootstrap/blob/master/LICENSE),documentation
underCCBY3.0(http://creativecommons.org/licenses/by/3.0/).
Currentlyv3.2.0 GitHub(https://github.com/twbs/bootstrap) Examples(../getting
started/#examples) v2.3.2docs(../2.3.2/) About(../about/) Expo
(http://expo.getbootstrap.com) Blog(http://blog.getbootstrap.com) Issues
(https://github.com/twbs/bootstrap/issues?state=open) Releases
(https://github.com/twbs/bootstrap/releases)
Bootstrap'saffixclassexposesafeweventsforhookingintoaffixfunctionality.
EventType Description
affix.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixed.
affixed.bs.affix Thiseventisfiredaftertheelementhasbeenaffixed.
affixtop.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixedtop.
affixedtop.bs.affix Thiseventisfiredaftertheelementhasbeenaffixedtop.
affixbottom.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixedbottom.
affixed
bottom.bs.affix
Thiseventisfiredaftertheelementhasbeenaffixedbottom.

You might also like