Bootstrap 4 JavaScript Plugins Guide
Bootstrap 4 JavaScript Plugins Guide
JavaScript Bootstrap
Awwyeah,Bootstrap4iscoming!([Link]
JavaScript
BringBootstrap'scomponentstolifewithoveradozencustomjQuery
[Link],oronebyone.
([Link]
MonitorandIdentify,24x7,
sloworfailingproduction
JavaMethod,using
Germain
([Link]
6408111/)
adsviaCarbon
([Link]
Overview
Individualorcompiled
Pluginscanbeincludedindividually(usingBootstrap'sindividual *.jsfiles),orallatonce(using
[Link] [Link]).
UsingthecompiledJavaScript
Both [Link] [Link]
one.
Plugindependencies
[Link]
1/51
7/5/2016
JavaScript Bootstrap
[Link],
[Link]
jQuery(thismeansjQuerymustbeincludedbeforethepluginfiles).Consultour [Link]
([Link]
supported.
Dataattributes
YoucanuseallBootstrappluginspurelythroughthemarkupAPIwithoutwritingasinglelineof
[Link]'sfirstclassAPIandshouldbeyourfirstconsiderationwhenusinga
plugin.
Thatsaid,[Link],wealsoprovide
theabilitytodisablethedataattributeAPIbyunbindingalleventsonthedocumentnamespacedwith
[Link]:
$(document).off('.dataapi')
Alternatively,totargetaspecificplugin,justincludetheplugin'snameasanamespacealongwiththe
dataapinamespacelikethis:
$(document).off('.[Link]')
Onlyonepluginperelementviadataattributes
Don'[Link],abutton
[Link],useawrappingelement.
ProgrammaticAPI
[Link]
publicAPIsaresingle,chainablemethods,andreturnthecollectionactedupon.
$('.[Link]').button('toggle').addClass('fat')
Allmethodsshouldacceptanoptionaloptionsobject,astringwhichtargetsaparticularmethod,or
nothing(whichinitiatesapluginwithdefaultbehavior):
$('#myModal').modal()//initializedwithdefaults
$('#myModal').modal({keyboard:false})//initializedwithno
keyboard
$('#myModal').modal('show')//initializesandinvokes
showimmediately
[Link]
2/51
7/5/2016
JavaScript Bootstrap
Eachpluginalsoexposesitsrawconstructorona Constructorproperty:
$.[Link]'dliketogetaparticularplugininstance,retrieveitdirectlyfroman
element: $('[rel="popover"]').data('popover').
Defaultsettings
Youcanchangethedefaultsettingsforapluginbymodifyingtheplugin's [Link]
object:
$.[Link]=false//changesdefaultfor
themodalplugin's`keyboard`optiontofalse
Noconflict
[Link],
[Link],youmaycall .noConflictontheplugin
youwishtorevertthevalueof.
varbootstrapButton=$.[Link]()//return$.[Link]
previouslyassignedvalue
$.[Link]=bootstrapButton//give$().bootstrapBtn
theBootstrapfunctionality
Events
Bootstrapprovidescustomeventsformostplugins'[Link],thesecomeinan
infinitiveandpastparticipleformwheretheinfinitive(ex. show)istriggeredatthestartofanevent,
anditspastparticipleform(ex. shown)istriggeredonthecompletionofanaction.
Asof3.0.0,allBootstrapeventsarenamespaced.
Allinfinitiveeventsprovide [Link]
executionofanactionbeforeitstarts.
$('#myModal').on('[Link]',function(e){
if(!data)[Link]()//stopsmodalfrombeingshown
})
Versionnumbers
TheversionofeachofBootstrap'sjQuerypluginscanbeaccessedviathe VERSIONpropertyofthe
plugin'[Link],forthetooltipplugin:
$.[Link]//=>"3.3.6"
NospecialfallbackswhenJavaScriptis
disabled
[Link]
3/51
7/5/2016
JavaScript Bootstrap
Bootstrap'spluginsdon'[Link]
theuserexperienceinthiscase,use <noscript>([Link]
US/docs/Web/HTML/Element/noscript)toexplainthesituation(andhowtoreenableJavaScript)to
yourusers,and/oraddyourowncustomfallbacks.
Thirdpartylibraries
BootstrapdoesnotofficiallysupportthirdpartyJavaScriptlibrarieslikePrototypeor
[Link] .noConflictandnamespacedevents,theremaybecompatibility
problemsthatyouneedtofixonyourown.
[Link]
Abouttransitions
Forsimpletransitioneffects,include [Link]'reusing
thecompiled(orminified) [Link],thereisnoneedtoincludethisit'salreadythere.
What'sinside
[Link] [Link]'sused
bytheotherpluginstocheckforCSStransitionsupportandtocatchhangingtransitions.
Disablingtransitions
TransitionscanbegloballydisabledusingthefollowingJavaScriptsnippet,whichmustcomeafter
[Link](or [Link] [Link],asthecasemaybe)hasloaded:
$.[Link]=false
[Link]
Modalsarestreamlined,butflexible,dialogpromptswiththeminimumrequiredfunctionalityandsmart
defaults.
Multipleopenmodalsnotsupported
[Link]
4/51
7/5/2016
JavaScript Bootstrap
[Link]
timerequirescustomcode.
Modalmarkupplacement
Alwaystrytoplaceamodal'sHTMLcodeinatoplevelpositioninyourdocumenttoavoidother
componentsaffectingthemodal'sappearanceand/orfunctionality.
Mobiledevicecaveats
[Link]
docs(../gettingstarted/#supportfixedpositionkeyboards)fordetails.
DuetohowHTML5definesitssemantics,the autofocusHTMLattributehasnoeffectin
[Link],usesomecustomJavaScript:
$('#myModal').on('[Link]',function(){
$('#myInput').focus()
})
Examples
Staticexample
Arenderedmodalwithheader,body,andsetofactionsinthefooter.
EXAMPLE
Modaltitle
Onefinebody
Close
[Link]
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">×</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
[Link]
thepage.
EXAMPLE
Launchdemomodal
[Link]
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">×</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
[Link]
([Link]
information.
Optionalsizes
Modalshavetwooptionalsizes,availableviamodifierclassestobeplacedona .modaldialog.
[Link]
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
[Link]
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">×</span></button>
<h4class="modaltitle"id="gridSystemModalLabel">Modaltitle</h4>
</div>
<divclass="modalbody">
<divclass="row">
<divclass="colmd4">.colmd4</div>
<divclass="colmd4colmdoffset4">.[Link]
4</div>
</div>
<divclass="row">
<divclass="colmd3colmdoffset3">.[Link]
3</div>
<divclass="colmd2colmdoffset4">.[Link]
4</div>
</div>
<divclass="row">
<divclass="colmd6colmdoffset3">.[Link]
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
[Link]
9/51
7/5/2016
JavaScript Bootstrap
Haveabunchofbuttonsthatalltriggerthesamemodal,justwithslightlydifferentcontents?Use
[Link] data*attributes([Link]
US/docs/Web/Guide/HTML/Using_data_attributes)(possiblyviajQuery([Link]
[Link]
detailson relatedTarget,
EXAMPLE
[Link]
10/51
7/5/2016
JavaScript Bootstrap
$('#exampleModal').on('[Link]',function(event){
varbutton=$([Link])//Buttonthattriggeredthemodal
varrecipient=[Link]('whatever')//Extractinfofromdata*
attributes
//Ifnecessary,youcouldinitiateanAJAXrequesthere(andthendo
theupdatinginacallback).
//Updatethemodal'[Link]'llusejQueryhere,butyoucould
useadatabindinglibraryorothermethodsinstead.
varmodal=$(this)
[Link]('.modaltitle').text('Newmessageto'+recipient)
[Link]('.modalbodyinput').val(recipient)
})
Usage
Themodalplugintogglesyourhiddencontentondemand,[Link]
.modalopentothe <body>tooverridedefaultscrollingbehaviorandgeneratesa .modal
backdroptoprovideaclickareafordismissingshownmodalswhenclickingoutsidethemodal.
Viadataattributes
[Link] 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
[Link],appendtheoptionnameto
data,asin databackdrop="".
Name
type
default
description
backdrop
booleanor
thestring
true
[Link],specify
staticforabackdropwhichdoesn'tclosethemodalon
click.
'static'
keyboard
boolean
true
Closesthemodalwhenescapekeyispressed
show
boolean
true
Showsthemodalwheninitialized.
remote
path
false
[Link]
11/51
7/5/2016
JavaScript Bootstrap
Thisoptionisdeprecatedsincev3.3.0andhasbeen
[Link]
templatingoradatabindingframework,orcalling
[Link]([Link]
IfaremoteURLisprovided,contentwillbeloadedone
timeviajQuery's loadmethodandinjectedintothe
.[Link]'reusingthedataapi,you
mayalternativelyusethe hrefattributetospecifythe
[Link]:
<adatatoggle="modal"
href="[Link]"data
target="#modal">Clickme</a>
Methods
.modal(options)
[Link] object.
$('#myModal').modal({
keyboard:false
})
.modal('toggle')
[Link]
hidden([Link] [Link] [Link]).
$('#myModal').modal('toggle')
.modal('show')
[Link](i.e.
beforethe [Link]).
$('#myModal').modal('show')
.modal('hide')
[Link](i.e.
beforethe [Link]).
$('#myModal').modal('hide')
.modal('handleUpdate')
[Link]
12/51
7/5/2016
JavaScript Bootstrap
Readjuststhemodal'spositioningtocounterascrollbarincaseoneshouldappear,whichwouldmake
themodaljumptotheleft.
Onlyneededwhentheheightofthemodalchangeswhileitisopen.
$('#myModal').modal('handleUpdate')
Events
Bootstrap'smodalclassexposesafeweventsforhookingintomodalfunctionality.
Allmodaleventsarefiredatthemodalitself([Link] <divclass="modal">).
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe [Link]
causedbyaclick,theclickedelementisavailableasthe relatedTarget
propertyoftheevent.
[Link]
Thiseventisfiredwhenthemodalhasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).Ifcausedbyaclick,theclicked
elementisavailableasthe relatedTargetpropertyoftheevent.
[Link]
Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.
[Link]
Thiseventisfiredwhenthemodalhasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).
[Link]
Thiseventisfiredwhenthemodalhasloadedcontentusingthe remote
option.
$('#myModal').on('[Link]',function(e){
//dosomething...
})
[Link]
Examples
Adddropdownmenustonearlyanythingwiththissimpleplugin,includingthenavbar,tabs,andpills.
Withinanavbar
[Link]
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,[Link]
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>
[Link]
14/51
7/5/2016
JavaScript Bootstrap
<divclass="dropdown">
<aid="dLabel"datatarget="#"href="[Link]
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
[Link]
Thiseventfiresimmediatelywhentheshowinstancemethodiscalled.
[Link]
Thiseventisfiredwhenthedropdownhasbeenmadevisibletotheuser
(willwaitforCSStransitions,tocomplete).
[Link]
Thiseventisfiredimmediatelywhenthehideinstancemethodhasbeen
called.
[Link]
15/51
7/5/2016
[Link]
JavaScript Bootstrap
Thiseventisfiredwhenthedropdownhasfinishedbeinghiddenfromthe
user(willwaitforCSStransitions,tocomplete).
$('#myDropdown').on('[Link]',function(){
//dosomething
})
[Link]
Exampleinnavbar
[Link]
[Link]
well.
EXAMPLE
@fat
Adleggingskeytar,[Link].
[Link]'s
[Link],williamsburghoodieminimquiyou
probablyhaven'[Link]
tattooedaccusamus,credironybiodieselkeffiyehartisanullamcoconsequat.
@mdo
Veniammarfamustacheskateboard,[Link]
Usage
RequiresBootstrapnav
ScrollspycurrentlyrequirestheuseofaBootstrapnavcomponent(../components/#nav)for
properhighlightingofactivelinks.
ResolvableIDtargetsrequired
[Link],a <ahref="#home">home</a>
mustcorrespondtosomethingintheDOMlike <divid="home"></div>.
[Link]
16/51
7/5/2016
JavaScript Bootstrap
Non :visibletargetelementsignored
Targetelementsthatarenot :visibleaccordingtojQuery([Link]
selector/)willbeignoredandtheircorrespondingnavitemswillneverbehighlighted.
Requiresrelativepositioning
Nomattertheimplementationmethod,scrollspyrequirestheuseof position:relativeonthe
elementyou'[Link] <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')
})
[Link]
17/51
7/5/2016
JavaScript Bootstrap
Options
[Link],appendtheoptionnameto
data,asin dataoffset="".
Name
type
default
description
offset
number
10
Pixelstooffsetfromtopwhencalculatingpositionofscroll.
Events
EventType
Description
[Link]
Thiseventfireswheneveranewitembecomesactivatedbythescrollspy.
$('#myScrollspy').on('[Link]',function(){
//dosomething
})
[Link]
Exampletabs
Addquick,dynamictabfunctionalitytotransitionthroughpanesoflocalcontent,evenviadropdown
[Link].
EXAMPLE
Home
Profile
Dropdown
Rawdenimyouprobablyhaven'[Link],
[Link],williamsburgcarlesveganhelvetica.
[Link],quiirureterry
[Link],
butchervoluptatenisiqui.
Extendstabbednavigation
[Link]
18/51
7/5/2016
JavaScript Bootstrap
Thispluginextendsthetabbednavigationcomponent(../components/#navtabs)toadd
tabbableareas.
Usage
EnabletabbabletabsviaJavaScript(eachtabneedstobeactivatedindividually):
$('#myTabsa').click(function(e){
[Link]()
$(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"[Link] navand navtabsclassesto
Fadeeffect
[Link]
19/51
7/5/2016
JavaScript Bootstrap
Fadeeffect
Tomaketabsfadein,add .fadetoeach .[Link] .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
[Link] datatargetoran href
[Link],thetabsarethe <a>swith data
toggle="tab"attributes.
.tab('show')
[Link]
[Link]
hasactuallybeenshown([Link] [Link]).
$('#someTab').tab('show')
Events
Whenshowinganewtab,theeventsfireinthefollowingorder:
1. [Link](onthecurrentactivetab)
2. [Link](onthetobeshowntab)
3. [Link](onthepreviousactivetab,thesameoneasforthe [Link])
4. [Link](onthenewlyactivejustshowntab,thesameoneasforthe [Link]
event)
Ifnotabwasalreadyactive,thenthe [Link] [Link].
EventType
Description
[Link]
Thiseventfiresontabshow,[Link]
[Link] [Link]
thepreviousactivetab(ifavailable)respectively.
[Link]
[Link]
[Link] [Link]
thepreviousactivetab(ifavailable)respectively.
[Link]
20/51
7/5/2016
JavaScript Bootstrap
[Link]
Thiseventfireswhenanewtabistobeshown(andthusthepreviousactive
tabistobehidden).Use [Link] [Link]
targetthecurrentactivetabandthenewsoontobeactivetab,respectively.
[Link]
Thiseventfiresafteranewtabisshown(andthusthepreviousactivetabis
hidden).Use [Link] [Link]
previousactivetabandthenewactivetab,respectively.
$('a[datatoggle="tab"]').on('[Link]',function(e){
[Link]//newlyactivatedtab
[Link]//previousactivetab
})
[Link]
[Link],
whichdon'trelyonimages,useCSS3foranimations,anddataattributesforlocaltitlestorage.
Tooltipswithzerolengthtitlesareneverdisplayed.
Examples
Hoveroverthelinksbelowtoseetooltips:
EXAMPLE
Tightpantsnextlevelkeffiyehyouprobablyhaven'[Link]
[Link],mcsweeney'sfixiesustainable
[Link],cardigans
[Link],fourlokomcsweeney'scleansevegan
[Link],scenesterfarmtotablebanksyAustintwitterhandle
freegancredrawdenimsingleorigincoffeeviral.
Statictooltip
Fouroptionsareavailable:top,right,bottom,andleftaligned.
EXAMPLE
Tooltipontheleft
[Link]
Tooltiponthetop
Tooltiponthebottom
21/51
7/5/2016
JavaScript Bootstrap
Tooltipontheright
Fourdirections
EXAMPLE
<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
[Link]
22/51
7/5/2016
JavaScript Bootstrap
Multiplelinelinks
[Link]
[Link] 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.
[Link]
23/51
7/5/2016
JavaScript Bootstrap
Options
[Link],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
[Link],jQuery's
textmethodwillbeusedtoinsertcontent
[Link]'reworriedabout
XSSattacks.
placement
string|
function
'top'
Howtopositionthetooltiptop|bottom|left|
right|auto.
When"auto"isspecified,itwilldynamically
[Link],ifplacement
is"autoleft",thetooltipwilldisplaytotheleft
whenpossible,otherwiseitwilldisplayright.
Whenafunctionisusedtodeterminethe
placement,itiscalledwiththetooltipDOM
nodeasitsfirstargumentandthetriggering
[Link] this
contextissettothetooltipinstance.
selector
string
[Link]
false
Ifaselectorisprovided,tooltipobjectswillbe
[Link],
thisisusedtoenabledynamicHTMLcontent
[Link]
24/51
7/5/2016
JavaScript Bootstrap
([Link]
andaninformativeexample
([Link]
template
string
'<div
class="tooltip"
role="tooltip">
<div
class="tooltip
BaseHTMLtousewhencreatingthetooltip.
Thetooltip's titlewillbeinjectedintothe
.tooltipinner.
.tooltiparrowwillbecomethetooltip's
arrow"></div>
arrow.
<div
Theoutermostwrapperelementshouldhave
title
string|
function
''
Defaulttitlevalueif titleattributeisn't
present.
Ifafunctionisgiven,itwillbecalledwithits
thisreferencesettotheelementthatthe
tooltipisattachedto.
trigger
string
'hoverfocus'
Howtooltipistriggeredclick|hover|focus|
[Link]
separatethemwithaspace. manualcannot
becombinedwithanyothertrigger.
viewport
string|
object|
function
{selector:'body',
padding:0}
Keepsthetooltipwithintheboundsofthis
[Link]: viewport:'#viewport'
or {"selector":"#viewport",
"padding":0}
Ifafunctionisgiven,itiscalledwiththe
triggeringelementDOMnodeasitsonly
[Link] thiscontextissettothe
tooltipinstance.
Dataattributesforindividualtooltips
Optionsforindividualtooltipscanalternativelybespecifiedthroughtheuseofdataattributes,as
explainedabove.
Methods
$().tooltip(options)
[Link]
25/51
7/5/2016
JavaScript Bootstrap
Attachesatooltiphandlertoanelementcollection.
.tooltip('show')
Revealsanelement'[Link](i.e.
beforethe [Link]).Thisisconsidereda"manual"triggeringofthetooltip.
Tooltipswithzerolengthtitlesareneverdisplayed.
$('#element').tooltip('show')
.tooltip('hide')
Hidesanelement'[Link](i.e.
beforethe [Link]).Thisisconsidereda"manual"triggeringofthetooltip.
$('#element').tooltip('hide')
.tooltip('toggle')
Togglesanelement'[Link]
hidden([Link] [Link] [Link]).Thisisconsidered
a"manual"triggeringofthetooltip.
$('#element').tooltip('toggle')
.tooltip('destroy')
Hidesanddestroysanelement'[Link](whicharecreatedusingthe
selectoroption)cannotbeindividuallydestroyedondescendanttriggerelements.
$('#element').tooltip('destroy')
Events
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.
[Link]
Thiseventisfiredwhenthetooltiphasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).
[Link]
Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.
[Link]
Thiseventisfiredwhenthetooltiphasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).
[Link]
Thiseventisfiredafterthe [Link]
templatehasbeenaddedtotheDOM.
[Link]
26/51
7/5/2016
JavaScript Bootstrap
$('#myTooltip').on('[Link]',function(){
//dosomething
})
[Link]
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
[Link]
27/51
7/5/2016
JavaScript Bootstrap
Multiplelinelinks
[Link]
[Link] whitespace:
nowraptoyouranchorstoavoidthis.
Examples
Staticpopover
Fouroptionsareavailable:top,right,bottom,andleftaligned.
EXAMPLE
Popovertop
Popoverright
Sedposuereconsecteturestat
[Link].
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Sedposuereconsecteturestat
[Link].
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Popoverbottom
Popoverleft
Sedposuereconsecteturestat
[Link].
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Sedposuereconsecteturestat
[Link].
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.
Livedemo
EXAMPLE
Clicktotogglepopover
[Link]
28/51
7/5/2016
JavaScript Bootstrap
<buttontype="button"class="btnbtnlgbtndanger"datatoggle="popover"
title="Popovertitle"datacontent="Andhere'[Link]'s
[Link]?">Clicktotogglepopover</button>
Fourdirections
EXAMPLE
<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
([Link]
EXAMPLE
Dismissiblepopover
[Link]
29/51
7/5/2016
JavaScript Bootstrap
<atabindex="0"class="btnbtnlgbtndanger"role="button"data
toggle="popover"datatrigger="focus"title="Dismissiblepopover"data
content="Andhere'[Link]'sveryengaging.
Right?">Dismissiblepopover</a>
Usage
EnablepopoversviaJavaScript:
$('#example').popover(options)
Options
[Link],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
[Link]
false
[Link],jQuery's
textmethodwillbeusedtoinsertcontent
30/51
7/5/2016
JavaScript Bootstrap
[Link]'reworriedabout
XSSattacks.
placement
string|
function
'right'
Howtopositionthepopovertop|bottom|left
|right|auto.
When"auto"isspecified,itwilldynamically
[Link],ifplacement
is"autoleft",thepopoverwilldisplaytotheleft
whenpossible,otherwiseitwilldisplayright.
Whenafunctionisusedtodeterminethe
placement,itiscalledwiththepopoverDOM
nodeasitsfirstargumentandthetriggering
[Link] this
contextissettothepopoverinstance.
selector
string
template
string
false
'<div
class="popover"
role="tooltip">
<div
class="arrow">
</div><h3
class="popover
title"></h3>
Ifaselectorisprovided,popoverobjectswillbe
[Link],
thisisusedtoenabledynamicHTMLcontent
[Link]
([Link]
andaninformativeexample
([Link]
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
|[Link]
separatethemwithaspace. manualcannot
becombinedwithanyothertrigger.
[Link]
31/51
7/5/2016
viewport
JavaScript Bootstrap
string|
object|
function
{selector:'body',
padding:0}
Keepsthepopoverwithintheboundsofthis
[Link]: viewport:'#viewport'
or {"selector":"#viewport",
"padding":0}
Ifafunctionisgiven,itiscalledwiththe
triggeringelementDOMnodeasitsonly
[Link] thiscontextissettothe
popoverinstance.
Dataattributesforindividualpopovers
Optionsforindividualpopoverscanalternativelybespecifiedthroughtheuseofdataattributes,
asexplainedabove.
Methods
$().popover(options)
Initializespopoversforanelementcollection.
.popover('show')
Revealsanelement'[Link]
([Link] [Link]).Thisisconsidereda"manual"triggeringofthe
[Link].
$('#element').popover('show')
.popover('hide')
Hidesanelement'[Link]
([Link] [Link]).Thisisconsidereda"manual"triggeringofthe
popover.
$('#element').popover('hide')
.popover('toggle')
Togglesanelement'[Link]
orhidden([Link] [Link] [Link]).Thisis
considereda"manual"triggeringofthepopover.
$('#element').popover('toggle')
.popover('destroy')
[Link]
32/51
7/5/2016
JavaScript Bootstrap
Hidesanddestroysanelement'[Link](whicharecreatedusingthe
selectoroption)cannotbeindividuallydestroyedondescendanttriggerelements.
$('#element').popover('destroy')
Events
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.
[Link]
Thiseventisfiredwhenthepopoverhasbeenmadevisibletotheuser(will
waitforCSStransitionstocomplete).
[Link]
Thiseventisfiredimmediatelywhenthe hideinstancemethodhasbeen
called.
[Link]
Thiseventisfiredwhenthepopoverhasfinishedbeinghiddenfromtheuser
(willwaitforCSStransitionstocomplete).
[Link]
Thiseventisfiredafterthe [Link]
templatehasbeenaddedtotheDOM.
$('#myPopover').on('[Link]',function(){
//dosomething
})
[Link]
Examplealerts
Adddismissfunctionalitytoallalertmessageswiththisplugin.
Whenusinga .closebutton,itmustbethefirstchildofthe .alertdismissibleandnotext
contentmaycomebeforeitinthemarkup.
EXAMPLE
Holyguacamole!Bestcheckyoself,you'renotlookingtoogood.
Ohsnap!Yougotanerror!
[Link]
33/51
7/5/2016
JavaScript Bootstrap
[Link],estnoncommodoluctus,nisieratporttitor
ligula,[Link].
Takethisaction Ordothis
Usage
Justadd datadismiss="alert"toyourclosebuttontoautomaticallygiveanalertclosefunctionality.
ClosinganalertremovesitfromtheDOM.
<buttontype="button"class="close"datadismiss="alert"aria
label="Close">
<spanariahidden="true">×</span>
</button>
Methods
$().alert()
Makesanalertlistenforclickeventsondescendantelementswhichhavethe datadismiss="alert"
attribute.(Notnecessarywhenusingthedataapi'sautoinitialization.)
$().alert('close')
[Link] .fadeand .inclassesarepresentonthe
element,thealertwillfadeoutbeforeitisremoved.
Events
Bootstrap'salertpluginexposesafeweventsforhookingintoalertfunctionality.
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe closeinstancemethodiscalled.
[Link]
Thiseventisfiredwhenthealerthasbeenclosed(willwaitforCSS
transitionstocomplete).
$('#myAlert').on('[Link]',function(){
//dosomething
})
[Link]
34/51
7/5/2016
JavaScript Bootstrap
[Link]
[Link]
componentsliketoolbars.
Crossbrowsercompatibility
Firefoxpersistsformcontrolstates(disablednessandcheckedness)acrosspageloads
([Link]
autocomplete="off".SeeMozillabug#654072([Link]
id=654072).
Stateful
Add dataloadingtext="Loading..."tousealoadingstateonabutton.
Thisfeatureisdeprecatedsincev3.3.6andhasbeenremovedinv4.
Usewhicheverstateyoulike!
Forthesakeofthisdemonstration,weareusing dataloadingtextand
$().button('loading'),butthat'[Link]
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...
$[Link]('reset')
})
</script>
Singletoggle
[Link]
35/51
7/5/2016
JavaScript Bootstrap
Add datatoggle="button"toactivatetogglingonasinglebutton.
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
([Link] <inputtype="reset">orviasettingthe checkedpropertyoftheinput),youwill
needtotogglethe .activeclassontheinput's labelyourself.
EXAMPLE
Checkbox1(prechecked)
[Link]
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')
[Link].
$().button('reset')
[Link]
theresettinghasactuallycompleted.
$().button(string)
Swapstexttoanydatadefinedtextstate.
[Link]
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>
[Link]
Flexiblepluginthatutilizesahandfulofclassesforeasytogglebehavior.
Plugindependency
CollapserequiresthetransitionsplugintobeincludedinyourversionofBootstrap.
Example
Clickthebuttonsbelowtoshowandhideanotherelementviaclasschanges:
.collapsehidescontent
.collapsingisappliedduringtransitions
.[Link]
Linkwithhref Buttonwithdatatarget
[Link]
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,[Link]
laborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigin
[Link],craftbeerlaborewes
[Link]
occaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven'theard
ofthemaccusamuslaboresustainableVHS.
CollapsibleGroupItem#2
CollapsibleGroupItem#3
[Link]
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
[Link]
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
[Link],craftbeer
[Link]
[Link],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
[Link]
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
[Link],craftbeer
[Link]
[Link],rawdenim
aestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingThree">
<h4class="paneltitle">
[Link]
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
[Link]
3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
[Link],craftbeer
[Link]
[Link],rawdenim
aestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
</div>
Collapsiblelistgroup
Makeexpand/collapsecontrolsaccessible
Besuretoadd [Link]
[Link]
thecollapsibleelementisclosedbydefault,itshouldhaveavalueof aria
expanded="false".Ifyou'vesetthecollapsibleelementtobeopenbydefaultusingthe in
class,set ariaexpanded="true"[Link]
thisattributebasedonwhetherornotthecollapsibleelementhasbeenopenedorclosed.
Additionally,[Link] data
targetattributeispointingtoan idselectoryoumayaddanadditional ariacontrols
attributetothecontrolelement,containingthe [Link]
readersandsimilarassistivetechnologiesmakeuseofthisattributetoprovideuserswith
additionalshortcutstonavigatedirectlytothecollapsibleelementitself.
Usage
Thecollapsepluginutilizesafewclassestohandletheheavylifting:
.collapsehidesthecontent
.[Link]
[Link]
41/51
7/5/2016
JavaScript Bootstrap
.collapsingisaddedwhenthetransitionstarts,andremovedwhenitfinishes
Theseclassescanbefoundin [Link].
Viadataattributes
Justadd datatoggle="collapse"anda datatargettotheelementtoautomaticallyassign
[Link] datatargetattributeacceptsaCSSselectortoapplythe
[Link] [Link]'dlikeittodefault
open,addtheadditionalclass in.
Toaddaccordionlikegroupmanagementtoacollapsiblecontrol,addthedataattribute data
parent="#selector".Refertothedemotoseethisinaction.
ViaJavaScript
Enablemanuallywith:
$('.collapse').collapse()
Options
[Link],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)
[Link] object.
$('#myCollapsible').collapse({
toggle:false
})
.collapse('toggle')
[Link]
elementhasactuallybeenshownorhidden([Link] [Link]
[Link]).
[Link]
42/51
7/5/2016
JavaScript Bootstrap
.collapse('show')
[Link]
beenshown([Link] [Link]).
.collapse('hide')
[Link]
hidden([Link] [Link]).
Events
Bootstrap'scollapseclassexposesafeweventsforhookingintocollapsefunctionality.
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe showinstancemethodiscalled.
[Link]
Thiseventisfiredwhenacollapseelementhasbeenmadevisibletothe
user(willwaitforCSStransitionstocomplete).
[Link]
Thiseventisfiredimmediatelywhenthe hidemethodhasbeencalled.
[Link]
Thiseventisfiredwhenacollapseelementhasbeenhiddenfromtheuser
(willwaitforCSStransitionstocomplete).
$('#myCollapsible').on('[Link]',function(){
//dosomething
})
[Link]
Aslideshowcomponentforcyclingthroughelements,[Link]
supported.
Examples
[Link]
43/51
7/5/2016
JavaScript Bootstrap
EXAMPLE
Firstslide
[Link]
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
[Link]
becompliant,pleaseconsiderotheroptionsforpresentingyourcontent.
TransitionanimationsnotsupportedinInternetExplorer8&9
[Link]
45/51
7/5/2016
JavaScript Bootstrap
BootstrapexclusivelyusesCSS3foritsanimations,butInternetExplorer8&9don'tsupportthe
[Link],therearenoslidetransitionanimationswhenusingthese
[Link]
transitions.
Initialactiveelementrequired
The .[Link],thecarouselwillnotbe
visible.
Glyphiconiconsnotnecessary
The .[Link] .[Link]
[Link] .iconprevand
.iconnextasplainunicodealternatives.
Optionalcaptions
Addcaptionstoyourslideseasilywiththe .carouselcaptionelementwithinany .[Link]
aboutanyoptionalHTMLwithinthereanditwillbeautomaticallyalignedandformatted.
EXAMPLE
900x500
Firstslidelabel
Nullavitaeelitlibero,apharetraauguemollisinterdum.
[Link]
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
[Link],orwhenchangingacarousel's id,besureto
updatetherelevantcontrols.
Viadataattributes
Usedataattributestoeasilycontrolthepositionofthecarousel. dataslideacceptsthekeywords
prevor next,[Link],use data
slidetotopassarawslideindextothecarousel dataslideto="2",whichshiftstheslide
positiontoaparticularindexbeginningwith 0.
The dataride="carousel"[Link]
cannotbeusedincombinationwith(redundantandunnecessary)explicitJavaScript
initializationofthesamecarousel.
ViaJavaScript
Callcarouselmanuallywith:
$('.carousel').carousel()
Options
[Link],appendtheoptionnameto
data,asin datainterval="".
Name
type
default
description
interval
number
5000
Theamountoftimetodelaybetweenautomatically
[Link],carouselwillnotautomatically
cycle.
pause
string
"hover"
Pausesthecyclingofthecarouselonmouseenterand
resumesthecyclingofthecarouselonmouseleave.
wrap
boolean
true
Whetherthecarouselshouldcyclecontinuouslyorhave
hardstops.
[Link]
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([Link] <divclass="carousel">).
EventType
Description
[Link]
Thiseventfiresimmediatelywhenthe slideinstancemethodisinvoked.
[Link]
Thiseventisfiredwhenthecarouselhascompleteditsslidetransition.
$('#myCarousel').on('[Link]',function(){
//dosomething
})
[Link]
48/51
7/5/2016
JavaScript Bootstrap
[Link]
Example
Theaffixplugintoggles position:fixedonandoff,emulatingtheeffectfoundwith position:
sticky([Link]
subnavigationontherightisalivedemooftheaffixplugin.
Usage
[Link],you
mustprovideCSSforthepositioningandwidthofyouraffixedcontent.
Note:Donotusetheaffixpluginonanelementcontainedinarelativelypositionedelement,suchasa
pulledorpushedcolumn,duetoaSafarirenderingbug
([Link]
PositioningviaCSS
Theaffixplugintogglesbetweenthreeclasses,eachrepresentingaparticularstate: .affix, .affix
top,and .[Link],withtheexceptionof position:fixedon
.affix,fortheseclassesyourself(independentofthisplugin)tohandletheactualpositions.
Here'showtheaffixpluginworks:
[Link],thepluginadds .[Link]
pointnoCSSpositioningisrequired.
[Link]
.affixreplaces .affixtopandsets position:fixed(providedbyBootstrap'sCSS).
[Link],scrollingpastitshouldreplace .affixwith .[Link]
offsetsareoptional,[Link],add
position:[Link]
todeterminewheretopositiontheelementfromthere.
FollowtheabovestepstosetyourCSSforeitheroftheusageoptionsbelow.
Viadataattributes
Toeasilyaddaffixbehaviortoanyelement,justadd dataspy="affix"totheelementyouwantto
[Link].
<divdataspy="affix"dataoffsettop="60"dataoffsetbottom="200">
...
</div>
ViaJavaScript
[Link]
49/51
7/5/2016
JavaScript Bootstrap
CalltheaffixpluginviaJavaScript:
$('#myAffix').affix({
offset:{
top:100,
bottom:function(){
return([Link]=$('.footer').outerHeight(true))
}
}
})
Options
[Link],appendtheoptionnameto
data,asin dataoffsettop="200".
Name
type
default
description
offset
number|
function|
object
10
Pixelstooffsetfromscreenwhencalculatingpositionof
[Link],theoffsetwillbe
[Link]
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)
[Link] object.
$('#myAffix').affix({
offset:15
})
.affix('checkPosition')
Recalculatesthestateoftheaffixbasedonthedimensions,position,andscrollpositionoftherelevant
[Link] .affix, .affixtop,and .affixbottomclassesareaddedtoorremovedfromthe
[Link]
theaffixedcontentorthetargetelementarechanged,toensurecorrectpositioningoftheaffixed
content.
[Link]
50/51
7/5/2016
JavaScript Bootstrap
$('#myAffix').affix('checkPosition')
Events
Bootstrap'saffixpluginexposesafeweventsforhookingintoaffixfunctionality.
EventType
Description
[Link]
Thiseventfiresimmediatelybeforetheelementhasbeenaffixed.
[Link]
Thiseventisfiredaftertheelementhasbeenaffixed.
[Link]
Thiseventfiresimmediatelybeforetheelementhasbeenaffixedtop.
[Link]
Thiseventisfiredaftertheelementhasbeenaffixedtop.
[Link]
Thiseventfiresimmediatelybeforetheelementhasbeenaffixedbottom.
[Link]
Thiseventisfiredaftertheelementhasbeenaffixedbottom.
GitHub([Link] Twitter([Link]
Examples(../gettingstarted/#examples) About(../about/)
Designedandbuiltwithalltheloveintheworldby@mdo([Link]
([Link]
ofourcontributors([Link]
CodelicensedMIT([Link]
([Link]
[Link]
51/51