You are on page 1of 53

17/2/2017 JavaScriptBootstrap

Awwyeah,Bootstrap4iscoming!

JavaScript
BringBootstrap'scomponentstolifewithoveradozencustomjQueryplugins.Easilyincludethemall,oronebyone.

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

UsingthecompiledJavaScript
Both bootstrap.js and bootstrap.min.js containallpluginsinasinglefile.Includeonlyone.

Plugindependencies
SomepluginsandCSScomponentsdependonotherplugins.Ifyouincludepluginsindividually,makesuretocheckforthesedependenciesinthedocs.Alsonotethatall
pluginsdependonjQuery(thismeansjQuerymustbeincludedbeforethepluginfiles).Consultour bower.json toseewhichversionsofjQueryaresupported.

Dataattributes
YoucanuseallBootstrappluginspurelythroughthemarkupAPIwithoutwritingasinglelineofJavaScript.ThisisBootstrap'sfirstclassAPIandshouldbeyourfirstconsideration
whenusingaplugin.

Thatsaid,insomesituationsitmaybedesirabletoturnthisfunctionalityoff.Therefore,wealsoprovidetheabilitytodisablethedataattributeAPIbyunbindingalleventsonthe
documentnamespacedwith dataapi .Thislookslikethis:

$(document).off('.dataapi')

Alternatively,totargetaspecificplugin,justincludetheplugin'snameasanamespacealongwiththedataapinamespacelikethis:

$(document).off('.alert.dataapi')

http://getbootstrap.com/javascript/#collapseexample 1/53
17/2/2017 JavaScriptBootstrap

Onlyonepluginperelementviadataattributes
Don'tusedataattributesfrommultiplepluginsonthesameelement.Forexample,abuttoncannotbothhaveatooltipandtoggleamodal.Toaccomplishthis,usea
wrappingelement.

ProgrammaticAPI
WealsobelieveyoushouldbeabletouseallBootstrappluginspurelythroughtheJavaScriptAPI.AllpublicAPIsaresingle,chainablemethods,andreturnthecollectionacted
upon.

$('.btn.danger').button('toggle').addClass('fat')

Allmethodsshouldacceptanoptionaloptionsobject,astringwhichtargetsaparticularmethod,ornothing(whichinitiatesapluginwithdefaultbehavior):

$('#myModal').modal()//initializedwithdefaults
$('#myModal').modal({keyboard:false})//initializedwithnokeyboard
$('#myModal').modal('show')//initializesandinvokesshowimmediately

Eachpluginalsoexposesitsrawconstructorona Constructor property: $.fn.popover.Constructor .Ifyou'dliketogetaparticularplugininstance,retrieveitdirectlyfroman


element: $('[rel="popover"]').data('popover') .

Defaultsettings
Youcanchangethedefaultsettingsforapluginbymodifyingtheplugin's Constructor.DEFAULTS object:

$.fn.modal.Constructor.DEFAULTS.keyboard=false//changesdefaultforthemodalplugin's`keyboard`optiontofalse

Noconflict
SometimesitisnecessarytouseBootstrappluginswithotherUIframeworks.Inthesecircumstances,namespacecollisionscanoccasionallyoccur.Ifthishappens,youmaycall
.noConflict onthepluginyouwishtorevertthevalueof.

varbootstrapButton=$.fn.button.noConflict()//return$.fn.buttontopreviouslyassignedvalue
$.fn.bootstrapBtn=bootstrapButton//give$().bootstrapBtntheBootstrapfunctionality

Events
Bootstrapprovidescustomeventsformostplugins'uniqueactions.Generally,thesecomeinaninfinitiveandpastparticipleformwheretheinfinitive(ex. show )istriggeredatthe
startofanevent,anditspastparticipleform(ex. shown )istriggeredonthecompletionofanaction.

Asof3.0.0,allBootstrapeventsarenamespaced.

http://getbootstrap.com/javascript/#collapseexample 2/53
17/2/2017 JavaScriptBootstrap

Allinfinitiveeventsprovide preventDefault functionality.Thisprovidestheabilitytostoptheexecutionofanactionbeforeitstarts.

$('#myModal').on('show.bs.modal',function(e){
if(!data)returne.preventDefault()//stopsmodalfrombeingshown
})

Versionnumbers
TheversionofeachofBootstrap'sjQuerypluginscanbeaccessedviathe VERSION propertyoftheplugin'sconstructor.Forexample,forthetooltipplugin:

$.fn.tooltip.Constructor.VERSION//=>"3.3.7"

NospecialfallbackswhenJavaScriptisdisabled
Bootstrap'spluginsdon'tfallbackparticularlygracefullywhenJavaScriptisdisabled.Ifyoucareabouttheuserexperienceinthiscase,use <noscript> toexplainthesituation(and
howtoreenableJavaScript)toyourusers,and/oraddyourowncustomfallbacks.

Thirdpartylibraries
BootstrapdoesnotofficiallysupportthirdpartyJavaScriptlibrarieslikePrototypeorjQueryUI.Despite .noConflict andnamespacedevents,theremaybe
compatibilityproblemsthatyouneedtofixonyourown.

Transitionstransition.js
Abouttransitions
Forsimpletransitioneffects,include transition.js oncealongsidetheotherJSfiles.Ifyou'reusingthecompiled(orminified) bootstrap.js ,thereisnoneedtoincludethisit's
alreadythere.

What'sinside
Transition.jsisabasichelperfor transitionEnd eventsaswellasaCSStransitionemulator.It'susedbytheotherpluginstocheckforCSStransitionsupportandtocatchhanging
transitions.

Disablingtransitions
http://getbootstrap.com/javascript/#collapseexample 3/53
17/2/2017 JavaScriptBootstrap

TransitionscanbegloballydisabledusingthefollowingJavaScriptsnippet,whichmustcomeafter transition.js (or bootstrap.js or bootstrap.min.js ,asthecasemaybe)


hasloaded:

$.support.transition=false

Modalsmodal.js
Modalsarestreamlined,butflexible,dialogpromptswiththeminimumrequiredfunctionalityandsmartdefaults.

Multipleopenmodalsnotsupported
Besurenottoopenamodalwhileanotherisstillvisible.Showingmorethanonemodalatatimerequirescustomcode.

Modalmarkupplacement
Alwaystrytoplaceamodal'sHTMLcodeinatoplevelpositioninyourdocumenttoavoidothercomponentsaffectingthemodal'sappearanceand/orfunctionality.

Mobiledevicecaveats
Therearesomecaveatsregardingusingmodalsonmobiledevices.Seeourbrowsersupportdocsfordetails.

DuetohowHTML5definesitssemantics,the autofocus HTMLattributehasnoeffectinBootstrapmodals.Toachievethesameeffect,usesomecustomJavaScript:

$('#myModal').on('shown.bs.modal',function(){
$('#myInput').focus()
})

Examples
Staticexample
Arenderedmodalwithheader,body,andsetofactionsinthefooter.

EXA MPLE

http://getbootstrap.com/javascript/#collapseexample 4/53
17/2/2017 JavaScriptBootstrap

Modaltitle

Onefinebody

Close Savechanges

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

Livedemo
ToggleamodalviaJavaScriptbyclickingthebuttonbelow.Itwillslidedownandfadeinfromthetopofthepage.

EXA MPLE

Launchdemomodal

http://getbootstrap.com/javascript/#collapseexample 5/53
17/2/2017 JavaScriptBootstrap

<!Buttontriggermodal>
<buttontype="button"class="btnbtnprimarybtnlg"datatoggle="modal"datatarget="#myModal">
Launchdemomodal
</button>

<!Modal>
<divclass="modalfade"id="myModal"tabindex="1"role="dialog"arialabelledby="myModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"arialabel="Close"><spanariahidden="true">&times;</span></button>
<h4class="modaltitle"id="myModalLabel">Modaltitle</h4>
</div>
<divclass="modalbody">
...
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"datadismiss="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 .modaldialog itself.

Additionally,youmaygiveadescriptionofyourmodaldialogwith ariadescribedby on .modal .

EmbeddingYouTubevideos
EmbeddingYouTubevideosinmodalsrequiresadditionalJavaScriptnotinBootstraptoautomaticallystopplaybackandmore.SeethishelpfulStackOverflowpostformore
information.

Optionalsizes
Modalshavetwooptionalsizes,availableviamodifierclassestobeplacedona .modaldialog .

EXA MPLE

Largemodal Smallmodal

http://getbootstrap.com/javascript/#collapseexample 6/53
17/2/2017 JavaScriptBootstrap

<!Largemodal>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"datatarget=".bsexamplemodallg">Largemodal</button>

<divclass="modalfadebsexamplemodallg"tabindex="1"role="dialog"arialabelledby="myLargeModalLabel">
<divclass="modaldialogmodallg"role="document">
<divclass="modalcontent">
...
</div>
</div>
</div>

<!Smallmodal>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"datatarget=".bsexamplemodalsm">Smallmodal</button>

<divclass="modalfadebsexamplemodalsm"tabindex="1"role="dialog"arialabelledby="mySmallModalLabel">
<divclass="modaldialogmodalsm"role="document">
<divclass="modalcontent">
...
</div>
</div>
</div>

Removeanimation
Formodalsthatsimplyappearratherthanfadeintoview,removethe .fade classfromyourmodalmarkup.

<divclass="modal"tabindex="1"role="dialog"arialabelledby="...">
...
</div>

Usingthegridsystem
TotakeadvantageoftheBootstrapgridsystemwithinamodal,justnest .row swithinthe .modalbody andthenusethenormalgridsystemclasses.

EXA MPLE

Launchdemomodal

http://getbootstrap.com/javascript/#collapseexample 7/53
17/2/2017 JavaScriptBootstrap

<divclass="modalfade"tabindex="1"role="dialog"arialabelledby="gridSystemModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"arialabel="Close"><spanariahidden="true">&times;</span></button>
<h4class="modaltitle"id="gridSystemModalLabel">Modaltitle</h4>
</div>
<divclass="modalbody">
<divclass="row">
<divclass="colmd4">.colmd4</div>
<divclass="colmd4colmdoffset4">.colmd4.colmdoffset4</div>
</div>
<divclass="row">
<divclass="colmd3colmdoffset3">.colmd3.colmdoffset3</div>
<divclass="colmd2colmdoffset4">.colmd2.colmdoffset4</div>
</div>
<divclass="row">
<divclass="colmd6colmdoffset3">.colmd6.colmdoffset3</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"datadismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Savechanges</button>
</div>
</div><!/.modalcontent>
</div><!/.modaldialog>
</div><!/.modal>

Varyingmodalcontentbasedontriggerbutton
Haveabunchofbuttonsthatalltriggerthesamemodal,justwithslightlydifferentcontents?Use event.relatedTarget andHTML data* attributes(possiblyviajQuery)tovary
thecontentsofthemodaldependingonwhichbuttonwasclicked.SeetheModalEventsdocsfordetailson relatedTarget ,

http://getbootstrap.com/javascript/#collapseexample 8/53
17/2/2017 JavaScriptBootstrap

EXA MPLE

Openmodalfor@mdo Openmodalfor@fat Openmodalfor@getbootstrap ...morebuttons...

<buttontype="button"class="btnbtnprimary"datatoggle="modal"datatarget="#exampleModal"datawhatever="@mdo">Openmodalfor@mdo</button>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"datatarget="#exampleModal"datawhatever="@fat">Openmodalfor@fat</button>
<buttontype="button"class="btnbtnprimary"datatoggle="modal"datatarget="#exampleModal"datawhatever="@getbootstrap">Openmodalfor
@getbootstrap</button>
...morebuttons...

<divclass="modalfade"id="exampleModal"tabindex="1"role="dialog"arialabelledby="exampleModalLabel">
<divclass="modaldialog"role="document">
<divclass="modalcontent">
<divclass="modalheader">
<buttontype="button"class="close"datadismiss="modal"arialabel="Close"><spanariahidden="true">&times;</span></button>
<h4class="modaltitle"id="exampleModalLabel">Newmessage</h4>
</div>
<divclass="modalbody">
<form>
<divclass="formgroup">
<labelfor="recipientname"class="controllabel">Recipient:</label>
<inputtype="text"class="formcontrol"id="recipientname">
</div>
<divclass="formgroup">
<labelfor="messagetext"class="controllabel">Message:</label>
<textareaclass="formcontrol"id="messagetext"></textarea>
</div>
</form>
</div>
<divclass="modalfooter">
<buttontype="button"class="btnbtndefault"datadismiss="modal">Close</button>
<buttontype="button"class="btnbtnprimary">Sendmessage</button>
</div>
</div>
</div>
</div>

http://getbootstrap.com/javascript/#collapseexample 9/53
17/2/2017 JavaScriptBootstrap

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

Usage
Themodalplugintogglesyourhiddencontentondemand,viadataattributesorJavaScript.Italsoadds .modalopen tothe <body> tooverridedefaultscrollingbehaviorand
generatesa .modalbackdrop toprovideaclickareafordismissingshownmodalswhenclickingoutsidethemodal.

Viadataattributes
ActivateamodalwithoutwritingJavaScript.Set datatoggle="modal" onacontrollerelement,likeabutton,alongwitha datatarget="#foo" or href="#foo" totargetaspecific
modaltotoggle.

<buttontype="button"datatoggle="modal"datatarget="#myModal">Launchmodal</button>

ViaJavaScript
Callamodalwithid myModal withasinglelineofJavaScript:

$('#myModal').modal(options)

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

Name type default description

backdrop booleanor true Includesamodalbackdropelement.Alternatively,specify static forabackdropwhichdoesn'tclosethemodalonclick.


thestring
'static'

keyboard boolean true Closesthemodalwhenescapekeyispressed

show boolean true Showsthemodalwheninitialized.

http://getbootstrap.com/javascript/#collapseexample 10/53
17/2/2017 JavaScriptBootstrap

Name type default description

remote path false Thisoptionisdeprecatedsincev3.3.0andhasbeenremovedinv4.Werecommendinsteadusingclientsidetemplatingoradata


bindingframework,orcallingjQuery.loadyourself.

IfaremoteURLisprovided,contentwillbeloadedonetimeviajQuery's load methodandinjectedintothe .modalcontent div.If


you'reusingthedataapi,youmayalternativelyusethe href attributetospecifytheremotesource.Anexampleofthisisshown
below:

<adatatoggle="modal"href="remote.html"datatarget="#modal">Clickme</a>

Methods
.modal(options)
Activatesyourcontentasamodal.Acceptsanoptionaloptions object .

$('#myModal').modal({
keyboard:false
})

.modal('toggle')
Manuallytogglesamodal.Returnstothecallerbeforethemodalhasactuallybeenshownorhidden(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')

.modal('handleUpdate')
Readjuststhemodal'spositioningtocounterascrollbarincaseoneshouldappear,whichwouldmakethemodaljumptotheleft.

Onlyneededwhentheheightofthemodalchangeswhileitisopen.

http://getbootstrap.com/javascript/#collapseexample 11/53
17/2/2017 JavaScriptBootstrap

$('#myModal').modal('handleUpdate')

Events
Bootstrap'smodalclassexposesafeweventsforhookingintomodalfunctionality.

Allmodaleventsarefiredatthemodalitself(i.e.atthe <divclass="modal"> ).

EventType Description

show.bs.modal Thiseventfiresimmediatelywhenthe show instancemethodiscalled.Ifcausedbyaclick,theclickedelementisavailableasthe relatedTarget


propertyoftheevent.

shown.bs.modal Thiseventisfiredwhenthemodalhasbeenmadevisibletotheuser(willwaitforCSStransitionstocomplete).Ifcausedbyaclick,theclickedelementis
availableasthe relatedTarget propertyoftheevent.

hide.bs.modal Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeencalled.

hidden.bs.modal Thiseventisfiredwhenthemodalhasfinishedbeinghiddenfromtheuser(willwaitforCSStransitionstocomplete).

loaded.bs.modal Thiseventisfiredwhenthemodalhasloadedcontentusingthe remote option.

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

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

Withinanavbar
EXA MPLE

Withinpills
http://getbootstrap.com/javascript/#collapseexample 12/53
17/2/2017 JavaScriptBootstrap

Withinpills
EXA MPLE

Regularlink Dropdown Dropdown Dropdown

Usage
ViadataattributesorJavaScript,thedropdownplugintoggleshiddencontent(dropdownmenus)bytogglingthe .open classontheparentlistitem.

Onmobiledevices,openingadropdownaddsa .dropdownbackdrop asatapareaforclosingdropdownmenuswhentappingoutsidethemenu,arequirementforproperiOS


support.Thismeansthatswitchingfromanopendropdownmenutoadifferentdropdownmenurequiresanextrataponmobile.

Note:The datatoggle="dropdown" attributeisreliedonforclosingdropdownmenusatanapplicationlevel,soit'sagoodideatoalwaysuseit.

Viadataattributes
Add datatoggle="dropdown" toalinkorbuttontotoggleadropdown.

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

TokeepURLsintactwithlinkbuttons,usethe datatarget attributeinsteadof href="#" .

<divclass="dropdown">
<aid="dLabel"datatarget="#"href="http://example.com"datatoggle="dropdown"role="button"ariahaspopup="true"ariaexpanded="false">
Dropdowntrigger
<spanclass="caret"></span>
</a>

<ulclass="dropdownmenu"arialabelledby="dLabel">
...
</ul>
</div>

ViaJavaScript
http://getbootstrap.com/javascript/#collapseexample 13/53
17/2/2017 JavaScriptBootstrap

CallthedropdownsviaJavaScript:

$('.dropdowntoggle').dropdown()

datatoggle="dropdown" stillrequired
RegardlessofwhetheryoucallyourdropdownviaJavaScriptorinsteadusethedataapi, datatoggle="dropdown" isalwaysrequiredtobepresentonthedropdown's
triggerelement.

Options
None

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

Events
Alldropdowneventsarefiredatthe .dropdownmenu 'sparentelement.

Alldropdowneventshavea relatedTarget property,whosevalueisthetogglinganchorelement.

EventType Description

show.bs.dropdown Thiseventfiresimmediatelywhentheshowinstancemethodiscalled.

shown.bs.dropdown Thiseventisfiredwhenthedropdownhasbeenmadevisibletotheuser(willwaitforCSStransitions,tocomplete).

hide.bs.dropdown Thiseventisfiredimmediatelywhenthehideinstancemethodhasbeencalled.

hidden.bs.dropdown Thiseventisfiredwhenthedropdownhasfinishedbeinghiddenfromtheuser(willwaitforCSStransitions,tocomplete).

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

http://getbootstrap.com/javascript/#collapseexample 14/53
17/2/2017 JavaScriptBootstrap

ScrollSpyscrollspy.js
Exampleinnavbar
TheScrollSpypluginisforautomaticallyupdatingnavtargetsbasedonscrollposition.Scrolltheareabelowthenavbarandwatchtheactiveclasschange.Thedropdownsubitems
willbehighlightedaswell.

EXA MPLE

@fat
Adleggingskeytar,brunchidartpartydolorlabore.Pitchforkyrenimlofibeforetheysoldoutqui.Tumblrfarmtotablebicyclerightswhatever.Animkeffiyehcarlescardigan.
Velitseitanmcsweeney'sphotobooth3wolfmoonirure.Cosbysweaterlomojeanshorts,williamsburghoodieminimquiyouprobablyhaven'theardofthemetcardigantrust
fundculpabiodieselwesandersonaesthetic.Nihiltattooedaccusamus,credironybiodieselkeffiyehartisanullamcoconsequat.

@mdo
Veniammarfamustacheskateboard,adipisicingfugiatvelitpitchforkbeard.Freeganbeardaliquacupidatatmcsweeney'svero.Cupidatatfourlokonisi,eahelveticanullacarles.
Tattooedcosbysweaterfoodtruck,mcsweeney'squisnonfreeganvinyl.Lofiwesanderson+1sartorial.Carlesnonaestheticexercitationquisgentrify.Brooklynadipisicingcraft
beervicekeytardeserunt.

Usage

RequiresBootstrapnav
ScrollspycurrentlyrequirestheuseofaBootstrapnavcomponentforproperhighlightingofactivelinks.

ResolvableIDtargetsrequired
Navbarlinksmusthaveresolvableidtargets.Forexample,a <ahref="#home">home</a> mustcorrespondtosomethingintheDOMlike <divid="home"></div> .

Non :visible targetelementsignored


Targetelementsthatarenot :visible accordingtojQuerywillbeignoredandtheircorrespondingnavitemswillneverbehighlighted.

Requiresrelativepositioning
http://getbootstrap.com/javascript/#collapseexample 15/53
17/2/2017 JavaScriptBootstrap

Nomattertheimplementationmethod,scrollspyrequirestheuseof position:relative; ontheelementyou'respyingon.Inmostcasesthisisthe <body> .Whenscrollspyingon


elementsotherthanthe <body> ,besuretohavea height setand overflowy:scroll; applied.

Viadataattributes
Toeasilyaddscrollspybehaviortoyourtopbarnavigation,add dataspy="scroll" totheelementyouwanttospyon(mosttypicallythiswouldbethe <body> ).Thenaddthe
datatarget attributewiththeIDorclassoftheparentelementofanyBootstrap .nav component.

body{
position:relative;
}

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

ViaJavaScript
Afteradding position:relative; inyourCSS,callthescrollspyviaJavaScript:

$('body').scrollspy({target:'#navbarexample'})

Methods
.scrollspy('refresh')
WhenusingscrollspyinconjunctionwithaddingorremovingofelementsfromtheDOM,you'llneedtocalltherefreshmethodlikeso:

$('[dataspy="scroll"]').each(function(){
var$spy=$(this).scrollspy('refresh')
})

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

Name type default description

http://getbootstrap.com/javascript/#collapseexample 16/53
17/2/2017 JavaScriptBootstrap

offset number 10 Pixelstooffsetfromtopwhencalculatingpositionofscroll.

Events
EventType Description

activate.bs.scrollspy Thiseventfireswheneveranewitembecomesactivatedbythescrollspy.

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

Togglabletabstab.js
Exampletabs
Addquick,dynamictabfunctionalitytotransitionthroughpanesoflocalcontent,evenviadropdownmenus.Nestedtabsarenotsupported.

EXA MPLE

Home Profile Dropdown

Rawdenimyouprobablyhaven'theardofthemjeanshortsAustin.Nesciunttofustumptownaliqua,retrosynthmastercleanse.Mustacheclichetempor,williamsburgcarlesvegan
helvetica.Reprehenderitbutcherretrokeffiyehdreamcatchersynth.Cosbysweatereubanhmi,quiirureterryrichardsonexsquid.Aliquipplaceatsalviacillumiphone.Seitan
aliquipquiscardiganamericanapparel,butchervoluptatenisiqui.

Extendstabbednavigation
Thispluginextendsthetabbednavigationcomponenttoaddtabbableareas.

Usage
EnabletabbabletabsviaJavaScript(eachtabneedstobeactivatedindividually):
http://getbootstrap.com/javascript/#collapseexample 17/53
17/2/2017 JavaScriptBootstrap

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

Youcanactivateindividualtabsinseveralways:

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

Markup
YoucanactivateataborpillnavigationwithoutwritinganyJavaScriptbysimplyspecifying datatoggle="tab" or datatoggle="pill" onanelement.Addingthe nav and nav
tabs classestothetab ul willapplytheBootstraptabstyling,whileaddingthe nav and navpills classeswillapplypillstyling.

<div>

<!Navtabs>
<ulclass="navnavtabs"role="tablist">
<lirole="presentation"class="active"><ahref="#home"ariacontrols="home"role="tab"datatoggle="tab">Home</a></li>
<lirole="presentation"><ahref="#profile"ariacontrols="profile"role="tab"datatoggle="tab">Profile</a></li>
<lirole="presentation"><ahref="#messages"ariacontrols="messages"role="tab"datatoggle="tab">Messages</a></li>
<lirole="presentation"><ahref="#settings"ariacontrols="settings"role="tab"datatoggle="tab">Settings</a></li>
</ul>

<!Tabpanes>
<divclass="tabcontent">
<divrole="tabpanel"class="tabpaneactive"id="home">...</div>
<divrole="tabpanel"class="tabpane"id="profile">...</div>
<divrole="tabpanel"class="tabpane"id="messages">...</div>
<divrole="tabpanel"class="tabpane"id="settings">...</div>
</div>

</div>

Fadeeffect
Tomaketabsfadein,add .fade toeach .tabpane .Thefirsttabpanemustalsohave .in tomaketheinitialcontentvisible.

http://getbootstrap.com/javascript/#collapseexample 18/53
17/2/2017 JavaScriptBootstrap

<divclass="tabcontent">
<divrole="tabpanel"class="tabpanefadeinactive"id="home">...</div>
<divrole="tabpanel"class="tabpanefade"id="profile">...</div>
<divrole="tabpanel"class="tabpanefade"id="messages">...</div>
<divrole="tabpanel"class="tabpanefade"id="settings">...</div>
</div>

Methods
$().tab
Activatesatabelementandcontentcontainer.Tabshouldhaveeithera datatarget oran href targetingacontainernodeintheDOM.Intheaboveexamples,thetabsarethe
<a> swith datatoggle="tab" attributes.

.tab('show')
Selectsthegiventabandshowsitsassociatedcontent.Anyothertabthatwaspreviouslyselectedbecomesunselectedanditsassociatedcontentishidden.Returnstothecaller
beforethetabpanehasactuallybeenshown(i.e.beforethe shown.bs.tab eventoccurs).

$('#someTab').tab('show')

Events
Whenshowinganewtab,theeventsfireinthefollowingorder:

1. hide.bs.tab (onthecurrentactivetab)
2. show.bs.tab (onthetobeshowntab)
3. hidden.bs.tab (onthepreviousactivetab,thesameoneasforthe hide.bs.tab event)
4. shown.bs.tab (onthenewlyactivejustshowntab,thesameoneasforthe show.bs.tab event)

Ifnotabwasalreadyactive,thenthe hide.bs.tab and hidden.bs.tab eventswillnotbefired.

EventType Description

show.bs.tab Thiseventfiresontabshow,butbeforethenewtabhasbeenshown.Use event.target and event.relatedTarget totargettheactivetabandthe


previousactivetab(ifavailable)respectively.

shown.bs.tab Thiseventfiresontabshowafteratabhasbeenshown.Use event.target and event.relatedTarget totargettheactivetabandthepreviousactive


tab(ifavailable)respectively.

hide.bs.tab Thiseventfireswhenanewtabistobeshown(andthusthepreviousactivetabistobehidden).Use event.target and event.relatedTarget to


targetthecurrentactivetabandthenewsoontobeactivetab,respectively.

hidden.bs.tab Thiseventfiresafteranewtabisshown(andthusthepreviousactivetabishidden).Use event.target and event.relatedTarget totargetthe


previousactivetabandthenewactivetab,respectively.

http://getbootstrap.com/javascript/#collapseexample 19/53
17/2/2017 JavaScriptBootstrap

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

Tooltipstooltip.js
InspiredbytheexcellentjQuery.tipsypluginwrittenbyJasonFrameTooltipsareanupdatedversion,whichdon'trelyonimages,useCSS3foranimations,anddataattributesfor
localtitlestorage.

Tooltipswithzerolengthtitlesareneverdisplayed.

Examples
Hoveroverthelinksbelowtoseetooltips:

EXA MPLE

Tightpantsnextlevelkeffiyehyouprobablyhaven'theardofthem.Photoboothbeardrawdenimletterpressveganmessengerbagstumptown.Farmtotableseitan,mcsweeney's
fixiesustainablequinoa8bitamericanapparelhaveaterryrichardsonvinylchambray.Beardstumptown,cardigansbanhmilomothundercats.Tofubiodieselwilliamsburgmarfa,
fourlokomcsweeney'scleanseveganchambray.Areallyironicartisanwhateverkeytar,scenesterfarmtotablebanksyAustintwitterhandlefreegancredrawdenimsingleorigin
coffeeviral.

Statictooltip
Fouroptionsareavailable:top,right,bottom,andleftaligned.

EXA MPLE

Tooltipontheleft Tooltiponthetop Tooltiponthebottom Tooltipontheright

Fourdirections

http://getbootstrap.com/javascript/#collapseexample 20/53
17/2/2017 JavaScriptBootstrap

EXA MPLE

Tooltiponleft Tooltipontop Tooltiponbottom Tooltiponright

<buttontype="button"class="btnbtndefault"datatoggle="tooltip"dataplacement="left"title="Tooltiponleft">Tooltiponleft</button>

<buttontype="button"class="btnbtndefault"datatoggle="tooltip"dataplacement="top"title="Tooltipontop">Tooltipontop</button>

<buttontype="button"class="btnbtndefault"datatoggle="tooltip"dataplacement="bottom"title="Tooltiponbottom">Tooltiponbottom</button>

<buttontype="button"class="btnbtndefault"datatoggle="tooltip"dataplacement="right"title="Tooltiponright">Tooltiponright</button>

Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumustinitializethemyourself.

Onewaytoinitializealltooltipsonapagewouldbetoselectthembytheir datatoggle attribute:

$(function(){
$('[datatoggle="tooltip"]').tooltip()
})

Usage
Thetooltipplugingeneratescontentandmarkupondemand,andbydefaultplacestooltipsaftertheirtriggerelement.

TriggerthetooltipviaJavaScript:

$('#example').tooltip(options)

Markup
Therequiredmarkupforatooltipisonlya data attributeand title ontheHTMLelementyouwishtohaveatooltip.Thegeneratedmarkupofatooltipisrathersimple,thoughit
doesrequireaposition(bydefault,setto top bytheplugin).

http://getbootstrap.com/javascript/#collapseexample 21/53
17/2/2017 JavaScriptBootstrap

<!HTMLtowrite>
<ahref="#"datatoggle="tooltip"title="Sometooltiptext!">Hoveroverme</a>

<!Generatedmarkupbytheplugin>
<divclass="tooltiptop"role="tooltip">
<divclass="tooltiparrow"></div>
<divclass="tooltipinner">
Sometooltiptext!
</div>
</div>

Multiplelinelinks
Sometimesyouwanttoaddatooltiptoahyperlinkthatwrapsmultiplelines.Thedefaultbehaviorofthetooltippluginistocenterithorizontallyandvertically.Add white
space:nowrap; toyouranchorstoavoidthis.

Tooltipsinbuttongroups,inputgroups,andtablesrequirespecialsetting
Whenusingtooltipsonelementswithina .btngroup oran .inputgroup ,orontablerelatedelements( <td> , <th> , <tr> , <thead> , <tbody> , <tfoot> ),you'llhaveto
specifytheoption container:'body' (documentedbelow)toavoidunwantedsideeffects(suchastheelementgrowingwiderand/orlosingitsroundedcornerswhenthe
tooltipistriggered).

Don'ttrytoshowtooltipsonhiddenelements
Invoking $(...).tooltip('show') whenthetargetelementis display:none; willcausethetooltiptobeincorrectlypositioned.

Accessibletooltipsforkeyboardandassistivetechnologyusers
Forusersnavigatingwithakeyboard,andinparticularusersofassistivetechnologies,youshouldonlyaddtooltipstokeyboardfocusableelementssuchaslinks,form
controls,oranyarbitraryelementwitha tabindex="0" attribute.

Tooltipsondisabledelementsrequirewrapperelements
Toaddatooltiptoa disabled or .disabled element,puttheelementinsideofa <div> andapplythetooltiptothat <div> instead.

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

http://getbootstrap.com/javascript/#collapseexample 22/53
17/2/2017 JavaScriptBootstrap

Name Type Default Description

animation boolean true ApplyaCSSfadetransitiontothetooltip

container string|false false Appendsthetooltiptoaspecificelement.Example: container:'body' .Thisoptionisparticularlyusefulinthatitallowsyou


topositionthetooltipintheflowofthedocumentnearthetriggeringelementwhichwillpreventthetooltipfromfloatingaway
fromthetriggeringelementduringawindowresize.

delay number| 0 Delayshowingandhidingthetooltip(ms)doesnotapplytomanualtriggertype


object
Ifanumberissupplied,delayisappliedtobothhide/show

Objectstructureis: delay:{"show":500,"hide":100}

html boolean false InsertHTMLintothetooltip.Iffalse,jQuery's text methodwillbeusedtoinsertcontentintotheDOM.Usetextifyou're


worriedaboutXSSattacks.

placement string| 'top' Howtopositionthetooltiptop|bottom|left|right|auto.


function When"auto"isspecified,itwilldynamicallyreorientthetooltip.Forexample,ifplacementis"autoleft",thetooltipwilldisplayto
theleftwhenpossible,otherwiseitwilldisplayright.

Whenafunctionisusedtodeterminetheplacement,itiscalledwiththetooltipDOMnodeasitsfirstargumentandthe
triggeringelementDOMnodeasitssecond.The this contextissettothetooltipinstance.

selector string false Ifaselectorisprovided,tooltipobjectswillbedelegatedtothespecifiedtargets.Inpractice,thisisusedtoenabledynamic


HTMLcontenttohavetooltipsadded.Seethisandaninformativeexample.

template string '<div BaseHTMLtousewhencreatingthetooltip.


class="tooltip"
Thetooltip's title willbeinjectedintothe .tooltipinner .
role="tooltip">
<div .tooltiparrow willbecomethetooltip'sarrow.
class="tooltip
Theoutermostwrapperelementshouldhavethe .tooltip class.
arrow"></div>
<div
class="tooltip
inner"></div>
</div>'

title string| '' Defaulttitlevalueif title attributeisn'tpresent.


function
Ifafunctionisgiven,itwillbecalledwithits this referencesettotheelementthatthetooltipisattachedto.

trigger string 'hoverfocus' Howtooltipistriggeredclick|hover|focus|manual.Youmaypassmultipletriggersseparatethemwithaspace. manual


cannotbecombinedwithanyothertrigger.

http://getbootstrap.com/javascript/#collapseexample 23/53
17/2/2017 JavaScriptBootstrap

Name Type Default Description

viewport string| {selector:'body', Keepsthetooltipwithintheboundsofthiselement.Example: viewport:'#viewport' or {"selector":"#viewport",


object| padding:0} "padding":0}
function
Ifafunctionisgiven,itiscalledwiththetriggeringelementDOMnodeasitsonlyargument.The this contextissettothe
tooltipinstance.

Dataattributesforindividualtooltips
Optionsforindividualtooltipscanalternativelybespecifiedthroughtheuseofdataattributes,asexplainedabove.

Methods
$().tooltip(options)
Attachesatooltiphandlertoanelementcollection.

.tooltip('show')
Revealsanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenshown(i.e.beforethe shown.bs.tooltip eventoccurs).Thisisconsidereda"manual"
triggeringofthetooltip.Tooltipswithzerolengthtitlesareneverdisplayed.

$('#element').tooltip('show')

.tooltip('hide')
Hidesanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenhidden(i.e.beforethe hidden.bs.tooltip eventoccurs).Thisisconsidereda"manual"
triggeringofthetooltip.

$('#element').tooltip('hide')

.tooltip('toggle')
Togglesanelement'stooltip.Returnstothecallerbeforethetooltiphasactuallybeenshownorhidden(i.e.beforethe shown.bs.tooltip or hidden.bs.tooltip event
occurs).Thisisconsidereda"manual"triggeringofthetooltip.

$('#element').tooltip('toggle')

.tooltip('destroy')
Hidesanddestroysanelement'stooltip.Tooltipsthatusedelegation(whicharecreatedusingthe selector option)cannotbeindividuallydestroyedondescendanttrigger
elements.

http://getbootstrap.com/javascript/#collapseexample 24/53
17/2/2017 JavaScriptBootstrap

$('#element').tooltip('destroy')

Events
EventType Description

show.bs.tooltip Thiseventfiresimmediatelywhenthe show instancemethodiscalled.

shown.bs.tooltip Thiseventisfiredwhenthetooltiphasbeenmadevisibletotheuser(willwaitforCSStransitionstocomplete).

hide.bs.tooltip Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeencalled.

hidden.bs.tooltip Thiseventisfiredwhenthetooltiphasfinishedbeinghiddenfromtheuser(willwaitforCSStransitionstocomplete).

inserted.bs.tooltip Thiseventisfiredafterthe show.bs.tooltip eventwhenthetooltiptemplatehasbeenaddedtotheDOM.

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

Popoverspopover.js
Addsmalloverlaysofcontent,likethoseontheiPad,toanyelementforhousingsecondaryinformation.

Popoverswhosebothtitleandcontentarezerolengthareneverdisplayed.

Plugindependency
PopoversrequirethetooltipplugintobeincludedinyourversionofBootstrap.

Optinfunctionality
Forperformancereasons,theTooltipandPopoverdataapisareoptin,meaningyoumustinitializethemyourself.

Onewaytoinitializeallpopoversonapagewouldbetoselectthembytheir datatoggle attribute:

http://getbootstrap.com/javascript/#collapseexample 25/53
17/2/2017 JavaScriptBootstrap

$(function(){
$('[datatoggle="popover"]').popover()
})

Popoversinbuttongroups,inputgroups,andtablesrequirespecialsetting
Whenusingpopoversonelementswithina .btngroup oran .inputgroup ,orontablerelatedelements( <td> , <th> , <tr> , <thead> , <tbody> , <tfoot> ),you'llhave
tospecifytheoption container:'body' (documentedbelow)toavoidunwantedsideeffects(suchastheelementgrowingwiderand/orlosingitsroundedcornerswhenthe
popoveristriggered).

Don'ttrytoshowpopoversonhiddenelements
Invoking $(...).popover('show') whenthetargetelementis display:none; willcausethepopovertobeincorrectlypositioned.

Popoversondisabledelementsrequirewrapperelements
Toaddapopovertoa disabled or .disabled element,puttheelementinsideofa <div> andapplythepopovertothat <div> instead.

Multiplelinelinks
Sometimesyouwanttoaddapopovertoahyperlinkthatwrapsmultiplelines.Thedefaultbehaviorofthepopoverpluginistocenterithorizontallyandvertically.Add
whitespace:nowrap; toyouranchorstoavoidthis.

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

EXA MPLE

Popovertop Popoverright Popoverbottom

Sedposuereconsecteturestat Sedposuereconsecteturestat Sedposuereconsecteturestat


lobortis.Aeneaneuleoquam. lobortis.Aeneaneuleoquam. lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia Pellentesqueornaresemlacinia Pellentesqueornaresemlacinia
http://getbootstrap.com/javascript/#collapseexample 26/53
17/2/2017 JavaScriptBootstrap

quamvenenatisvestibulum. quamvenenatisvestibulum. quamvenenatisvestibulum.

Popoverleft

Sedposuereconsecteturestat
lobortis.Aeneaneuleoquam.
Pellentesqueornaresemlacinia
quamvenenatisvestibulum.

Livedemo
EXA MPLE

Clicktotogglepopover

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

Fourdirections

EXA MPLE

Popoveronright Popoverontop Popoveronbottom Popoveronleft

http://getbootstrap.com/javascript/#collapseexample 27/53
17/2/2017 JavaScriptBootstrap

<buttontype="button"class="btnbtndefault"datacontainer="body"datatoggle="popover"dataplacement="left"datacontent="Vivamussagittislacusvel
auguelaoreetrutrumfaucibus.">
Popoveronleft
</button>

<buttontype="button"class="btnbtndefault"datacontainer="body"datatoggle="popover"dataplacement="top"datacontent="Vivamussagittislacusvel
auguelaoreetrutrumfaucibus.">
Popoverontop
</button>

<buttontype="button"class="btnbtndefault"datacontainer="body"datatoggle="popover"dataplacement="bottom"datacontent="Vivamus
sagittislacusvelauguelaoreetrutrumfaucibus.">
Popoveronbottom
</button>

<buttontype="button"class="btnbtndefault"datacontainer="body"datatoggle="popover"dataplacement="right"datacontent="Vivamussagittislacusvel
auguelaoreetrutrumfaucibus.">
Popoveronright
</button>

Dismissonnextclick
Usethe focus triggertodismisspopoversonthenextclickthattheusermakes.

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

EXA MPLE

Dismissiblepopover

<atabindex="0"class="btnbtnlgbtndanger"role="button"datatoggle="popover"datatrigger="focus"title="Dismissiblepopover"datacontent="And
here'ssomeamazingcontent.It'sveryengaging.Right?">Dismissiblepopover</a>

Usage
EnablepopoversviaJavaScript:

$('#example').popover(options)

http://getbootstrap.com/javascript/#collapseexample 28/53
17/2/2017 JavaScriptBootstrap

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

Name Type Default Description

animation boolean true ApplyaCSSfadetransitiontothepopover

container string|false false Appendsthepopovertoaspecificelement.Example: container:'body' .Thisoptionisparticularlyusefulinthatitallows


youtopositionthepopoverintheflowofthedocumentnearthetriggeringelementwhichwillpreventthepopoverfrom
floatingawayfromthetriggeringelementduringawindowresize.

content string| '' Defaultcontentvalueif datacontent attributeisn'tpresent.


function
Ifafunctionisgiven,itwillbecalledwithits this referencesettotheelementthatthepopoverisattachedto.

delay number| 0 Delayshowingandhidingthepopover(ms)doesnotapplytomanualtriggertype


object
Ifanumberissupplied,delayisappliedtobothhide/show

Objectstructureis: delay:{"show":500,"hide":100}

html boolean false InsertHTMLintothepopover.Iffalse,jQuery's text methodwillbeusedtoinsertcontentintotheDOM.Usetextifyou're


worriedaboutXSSattacks.

placement string| 'right' Howtopositionthepopovertop|bottom|left|right|auto.


function When"auto"isspecified,itwilldynamicallyreorientthepopover.Forexample,ifplacementis"autoleft",thepopoverwill
displaytotheleftwhenpossible,otherwiseitwilldisplayright.

Whenafunctionisusedtodeterminetheplacement,itiscalledwiththepopoverDOMnodeasitsfirstargumentandthe
triggeringelementDOMnodeasitssecond.The this contextissettothepopoverinstance.

selector string false Ifaselectorisprovided,popoverobjectswillbedelegatedtothespecifiedtargets.Inpractice,thisisusedtoenabledynamic


HTMLcontenttohavepopoversadded.Seethisandaninformativeexample.

http://getbootstrap.com/javascript/#collapseexample 29/53
17/2/2017 JavaScriptBootstrap

Name Type Default Description

template string '<div BaseHTMLtousewhencreatingthepopover.


class="popover"
Thepopover's title willbeinjectedintothe .popovertitle .
role="tooltip">
<div Thepopover's content willbeinjectedintothe .popovercontent .
class="arrow">
.arrow willbecomethepopover'sarrow.
</div><h3
class="popover Theoutermostwrapperelementshouldhavethe .popover class.
title"></h3>
<div
class="popover
content"></div>
</div>'

title string| '' Defaulttitlevalueif title attributeisn'tpresent.


function
Ifafunctionisgiven,itwillbecalledwithits this referencesettotheelementthatthepopoverisattachedto.

trigger string 'click' Howpopoveristriggeredclick|hover|focus|manual.Youmaypassmultipletriggersseparatethemwithaspace. manual


cannotbecombinedwithanyothertrigger.

viewport string| {selector:'body', Keepsthepopoverwithintheboundsofthiselement.Example: viewport:'#viewport' or {"selector":"#viewport",


object| padding:0} "padding":0}
function
Ifafunctionisgiven,itiscalledwiththetriggeringelementDOMnodeasitsonlyargument.The this contextissettothe
popoverinstance.

Dataattributesforindividualpopovers
Optionsforindividualpopoverscanalternativelybespecifiedthroughtheuseofdataattributes,asexplainedabove.

Methods
$().popover(options)
Initializespopoversforanelementcollection.

.popover('show')
Revealsanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenshown(i.e.beforethe shown.bs.popover eventoccurs).Thisisconsidereda
"manual"triggeringofthepopover.Popoverswhosebothtitleandcontentarezerolengthareneverdisplayed.

http://getbootstrap.com/javascript/#collapseexample 30/53
17/2/2017 JavaScriptBootstrap

$('#element').popover('show')

.popover('hide')
Hidesanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenhidden(i.e.beforethe hidden.bs.popover eventoccurs).Thisisconsidereda
"manual"triggeringofthepopover.

$('#element').popover('hide')

.popover('toggle')
Togglesanelement'spopover.Returnstothecallerbeforethepopoverhasactuallybeenshownorhidden(i.e.beforethe shown.bs.popover or hidden.bs.popover event
occurs).Thisisconsidereda"manual"triggeringofthepopover.

$('#element').popover('toggle')

.popover('destroy')
Hidesanddestroysanelement'spopover.Popoversthatusedelegation(whicharecreatedusingthe selector option)cannotbeindividuallydestroyedondescendanttrigger
elements.

$('#element').popover('destroy')

Events
EventType Description

show.bs.popover Thiseventfiresimmediatelywhenthe show instancemethodiscalled.

shown.bs.popover Thiseventisfiredwhenthepopoverhasbeenmadevisibletotheuser(willwaitforCSStransitionstocomplete).

hide.bs.popover Thiseventisfiredimmediatelywhenthe hide instancemethodhasbeencalled.

hidden.bs.popover Thiseventisfiredwhenthepopoverhasfinishedbeinghiddenfromtheuser(willwaitforCSStransitionstocomplete).

inserted.bs.popover Thiseventisfiredafterthe show.bs.popover eventwhenthepopovertemplatehasbeenaddedtotheDOM.

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

http://getbootstrap.com/javascript/#collapseexample 31/53
17/2/2017 JavaScriptBootstrap

Alertmessagesalert.js
Examplealerts
Adddismissfunctionalitytoallalertmessageswiththisplugin.

Whenusinga .close button,itmustbethefirstchildofthe .alertdismissible andnotextcontentmaycomebeforeitinthemarkup.

EXA MPLE

Holyguacamole!Bestcheckyoself,you'renotlookingtoogood.

Ohsnap!Yougotanerror!
Changethisandthatandtryagain.Duismollis,estnoncommodoluctus,nisieratporttitorligula,egetlaciniaodiosemnecelit.Crasmattisconsecteturpurussitamet
fermentum.

Takethisaction Ordothis

Usage
Justadd datadismiss="alert" toyourclosebuttontoautomaticallygiveanalertclosefunctionality.ClosinganalertremovesitfromtheDOM.

<buttontype="button"class="close"datadismiss="alert"arialabel="Close">
<spanariahidden="true">&times;</span>
</button>

Tohaveyouralertsuseanimationwhenclosing,makesuretheyhavethe .fade and .in classesalreadyappliedtothem.

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

$().alert('close')
ClosesanalertbyremovingitfromtheDOM.Ifthe .fade and .in classesarepresentontheelement,thealertwillfadeoutbeforeitisremoved.

Events
http://getbootstrap.com/javascript/#collapseexample 32/53
17/2/2017 JavaScriptBootstrap

Bootstrap'salertpluginexposesafeweventsforhookingintoalertfunctionality.

EventType Description

close.bs.alert Thiseventfiresimmediatelywhenthe close instancemethodiscalled.

closed.bs.alert Thiseventisfiredwhenthealerthasbeenclosed(willwaitforCSStransitionstocomplete).

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

Buttonsbutton.js
Domorewithbuttons.Controlbuttonstatesorcreategroupsofbuttonsformorecomponentsliketoolbars.

Crossbrowsercompatibility
Firefoxpersistsformcontrolstates(disablednessandcheckedness)acrosspageloads.Aworkaroundforthisistouse autocomplete="off" .SeeMozillabug#654072.

Stateful
Add dataloadingtext="Loading..." tousealoadingstateonabutton.

Thisfeatureisdeprecatedsincev3.3.5andhasbeenremovedinv4.

Usewhicheverstateyoulike!
Forthesakeofthisdemonstration,weareusing dataloadingtext and $().button('loading') ,butthat'snottheonlystateyoucanuse.Seemoreonthisbelowinthe
$().button(string) documentation.

EXA MPLE

Loadingstate

http://getbootstrap.com/javascript/#collapseexample 33/53
17/2/2017 JavaScriptBootstrap

<buttontype="button"id="myButton"dataloadingtext="Loading..."class="btnbtnprimary"autocomplete="off">
Loadingstate
</button>

<script>
$('#myButton').on('click',function(){
var$btn=$(this).button('loading')
//businesslogic...
$btn.button('reset')
})
</script>

Singletoggle
Add datatoggle="button" toactivatetogglingonasinglebutton.

Pretoggledbuttonsneed .active and ariapressed="true"


Forpretoggledbuttons,youmustaddthe .active classandthe ariapressed="true" attributetothe button yourself.

EXA MPLE

Singletoggle

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

Checkbox/Radio
Add datatoggle="buttons" toa .btngroup containingcheckboxorradioinputstoenabletogglingintheirrespectivestyles.

Preselectedoptionsneed .active
Forpreselectedoptions,youmustaddthe .active classtotheinput's label yourself.

Visualcheckedstateonlyupdatedonclick

http://getbootstrap.com/javascript/#collapseexample 34/53
17/2/2017 JavaScriptBootstrap

Ifthecheckedstateofacheckboxbuttonisupdatedwithoutfiringa click eventonthebutton(e.g.via <inputtype="reset"> orviasettingthe checked propertyofthe


input),youwillneedtotogglethe .active classontheinput's label yourself.

EXA MPLE

Checkbox1(prechecked) Checkbox2 Checkbox3

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

EXA MPLE

Radio1(preselected) Radio2 Radio3

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

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

$().button('reset')
http://getbootstrap.com/javascript/#collapseexample 35/53
17/2/2017 JavaScriptBootstrap
$().button('reset')
Resetsbuttonstateswapstexttooriginaltext.Thismethodisasynchronousandreturnsbeforetheresettinghasactuallycompleted.

$().button(string)
Swapstexttoanydatadefinedtextstate.

<buttontype="button"id="myStateButton"datacompletetext="finished!"class="btnbtnprimary"autocomplete="off">
...
</button>

<script>
$('#myStateButton').on('click',function(){
$(this).button('complete')//buttontextwillbe"finished!"
})
</script>

Collapsecollapse.js
Flexiblepluginthatutilizesahandfulofclassesforeasytogglebehavior.

Plugindependency
CollapserequiresthetransitionsplugintobeincludedinyourversionofBootstrap.

Example
Clickthebuttonsbelowtoshowandhideanotherelementviaclasschanges:

.collapse hidescontent
.collapsing isappliedduringtransitions
.collapse.in showscontent

Youcanusealinkwiththe href attribute,orabuttonwiththe datatarget attribute.Inbothcases,the datatoggle="collapse" isrequired.

EXA MPLE

Linkwithhref Buttonwithdatatarget

http://getbootstrap.com/javascript/#collapseexample 36/53
17/2/2017 JavaScriptBootstrap

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

Accordionexample
Extendthedefaultcollapsebehaviortocreateanaccordionwiththepanelcomponent.

EXA MPLE

CollapsibleGroupItem#1

CollapsibleGroupItem#2

CollapsibleGroupItem#3

http://getbootstrap.com/javascript/#collapseexample 37/53
17/2/2017 JavaScriptBootstrap

<divclass="panelgroup"id="accordion"role="tablist"ariamultiselectable="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,enimeiusmodhighlifeaccusamusterryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeerlaborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingTwo">
<h4class="paneltitle">
<aclass="collapsed"role="button"datatoggle="collapse"dataparent="#accordion"href="#collapseTwo"ariaexpanded="false"aria
controls="collapseTwo">
CollapsibleGroupItem#2
</a>
</h4>
</div>
<divid="collapseTwo"class="panelcollapsecollapse"role="tabpanel"arialabelledby="headingTwo">
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamusterryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeerlaborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
<divclass="panelpaneldefault">
<divclass="panelheading"role="tab"id="headingThree">
<h4class="paneltitle">
<aclass="collapsed"role="button"datatoggle="collapse"dataparent="#accordion"href="#collapseThree"ariaexpanded="false"aria
controls="collapseThree">
CollapsibleGroupItem#3
</a>
</h4>
</div>
<divid="collapseThree"class="panelcollapsecollapse"role="tabpanel"arialabelledby="headingThree">
<divclass="panelbody">
http://getbootstrap.com/javascript/#collapseexample 38/53
17/2/2017 JavaScriptBootstrap
<divclass="panelbody">
Animpariaturclichereprehenderit,enimeiusmodhighlifeaccusamusterryrichardsonadsquid.3wolfmoonofficiaaute,noncupidatat
skateboarddolorbrunch.Foodtruckquinoanesciuntlaborumeiusmod.Brunch3wolfmoontempor,suntaliquaputabirdonitsquidsingleorigincoffee
nullaassumendashoreditchet.Nihilanimkeffiyehhelvetica,craftbeerlaborewesandersoncrednesciuntsapienteeaproident.Adveganexcepteur
butchervicelomo.Leggingsoccaecatcraftbeerfarmtotable,rawdenimaestheticsynthnesciuntyouprobablyhaven'theardofthemaccusamuslabore
sustainableVHS.
</div>
</div>
</div>
</div>

It'salsopossibletoswapout .panelbody swith .listgroup s.

Collapsiblelistgroup

Makeexpand/collapsecontrolsaccessible
Besuretoadd ariaexpanded tothecontrolelement.Thisattributeexplicitlydefinesthecurrentstateofthecollapsibleelementtoscreenreadersandsimilarassistive
technologies.Ifthecollapsibleelementisclosedbydefault,itshouldhaveavalueof ariaexpanded="false" .Ifyou'vesetthecollapsibleelementtobeopenbydefault
usingthe in class,set ariaexpanded="true" onthecontrolinstead.Thepluginwillautomaticallytogglethisattributebasedonwhetherornotthecollapsibleelementhas
beenopenedorclosed.

Additionally,ifyourcontrolelementistargetingasinglecollapsibleelementi.e.the datatarget attributeispointingtoan id selectoryoumayaddanadditional aria


controls attributetothecontrolelement,containingthe id ofthecollapsibleelement.Modernscreenreadersandsimilarassistivetechnologiesmakeuseofthisattribute
toprovideuserswithadditionalshortcutstonavigatedirectlytothecollapsibleelementitself.

Usage
Thecollapsepluginutilizesafewclassestohandletheheavylifting:

.collapse hidesthecontent
.collapse.in showsthecontent
.collapsing isaddedwhenthetransitionstarts,andremovedwhenitfinishes

Theseclassescanbefoundin componentanimations.less .

Viadataattributes
Justadd datatoggle="collapse" anda datatarget totheelementtoautomaticallyassigncontrolofacollapsibleelement.The datatarget attributeacceptsaCSSselectorto
applythecollapseto.Besuretoaddtheclass collapse tothecollapsibleelement.Ifyou'dlikeittodefaultopen,addtheadditionalclass in .

Toaddaccordionlikegroupmanagementtoacollapsiblecontrol,addthedataattribute dataparent="#selector" .Refertothedemotoseethisinaction.

ViaJavaScript

http://getbootstrap.com/javascript/#collapseexample 39/53
17/2/2017 JavaScriptBootstrap

Enablemanuallywith:

$('.collapse').collapse()

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

Name type default description

parent selector false Ifaselectorisprovided,thenallcollapsibleelementsunderthespecifiedparentwillbeclosedwhenthiscollapsibleitemisshown.


(similartotraditionalaccordionbehaviorthisisdependentonthe panel class)

toggle boolean true Togglesthecollapsibleelementoninvocation

Methods
.collapse(options)
Activatesyourcontentasacollapsibleelement.Acceptsanoptionaloptions object .

$('#myCollapsible').collapse({
toggle:false
})

.collapse('toggle')
Togglesacollapsibleelementtoshownorhidden.Returnstothecallerbeforethecollapsibleelementhasactuallybeenshownorhidden(i.e.beforethe
shown.bs.collapse or hidden.bs.collapse eventoccurs).

.collapse('show')
Showsacollapsibleelement.Returnstothecallerbeforethecollapsibleelementhasactuallybeenshown(i.e.beforethe shown.bs.collapse eventoccurs).

.collapse('hide')
Hidesacollapsibleelement.Returnstothecallerbeforethecollapsibleelementhasactuallybeenhidden(i.e.beforethe hidden.bs.collapse eventoccurs).

Events
Bootstrap'scollapseclassexposesafeweventsforhookingintocollapsefunctionality.

EventType Description

show.bs.collapse Thiseventfiresimmediatelywhenthe show instancemethodiscalled.

http://getbootstrap.com/javascript/#collapseexample 40/53
17/2/2017 JavaScriptBootstrap

EventType Description

shown.bs.collapse Thiseventisfiredwhenacollapseelementhasbeenmadevisibletotheuser(willwaitforCSStransitionstocomplete).

hide.bs.collapse Thiseventisfiredimmediatelywhenthe hide methodhasbeencalled.

hidden.bs.collapse Thiseventisfiredwhenacollapseelementhasbeenhiddenfromtheuser(willwaitforCSStransitionstocomplete).

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

Carouselcarousel.js
Aslideshowcomponentforcyclingthroughelements,likeacarousel.Nestedcarouselsarenotsupported.

Examples

http://getbootstrap.com/javascript/#collapseexample 41/53
17/2/2017 JavaScriptBootstrap

EXA MPLE


Firstslide

http://getbootstrap.com/javascript/#collapseexample 42/53
17/2/2017 JavaScriptBootstrap

<divid="carouselexamplegeneric"class="carouselslide"dataride="carousel">
<!Indicators>
<olclass="carouselindicators">
<lidatatarget="#carouselexamplegeneric"dataslideto="0"class="active"></li>
<lidatatarget="#carouselexamplegeneric"dataslideto="1"></li>
<lidatatarget="#carouselexamplegeneric"dataslideto="2"></li>
</ol>

<!Wrapperforslides>
<divclass="carouselinner"role="listbox">
<divclass="itemactive">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
...
</div>
</div>
<divclass="item">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
...
</div>
</div>
...
</div>

<!Controls>
<aclass="leftcarouselcontrol"href="#carouselexamplegeneric"role="button"dataslide="prev">
<spanclass="glyphiconglyphiconchevronleft"ariahidden="true"></span>
<spanclass="sronly">Previous</span>
</a>
<aclass="rightcarouselcontrol"href="#carouselexamplegeneric"role="button"dataslide="next">
<spanclass="glyphiconglyphiconchevronright"ariahidden="true"></span>
<spanclass="sronly">Next</span>
</a>
</div>

Accessibilityissue
Thecarouselcomponentisgenerallynotcompliantwithaccessibilitystandards.Ifyouneedtobecompliant,pleaseconsiderotheroptionsforpresentingyourcontent.

TransitionanimationsnotsupportedinInternetExplorer8&9
BootstrapexclusivelyusesCSS3foritsanimations,butInternetExplorer8&9don'tsupportthenecessaryCSSproperties.Thus,therearenoslidetransitionanimations
whenusingthesebrowsers.WehaveintentionallydecidednottoincludejQuerybasedfallbacksforthetransitions.

http://getbootstrap.com/javascript/#collapseexample 43/53
17/2/2017 JavaScriptBootstrap

Initialactiveelementrequired
The .active classneedstobeaddedtooneoftheslides.Otherwise,thecarouselwillnotbevisible.

Glyphiconiconsnotnecessary
The .glyphicon.glyphiconchevronleft and .glyphicon.glyphiconchevronright classesarenotnecessarilyneededforthecontrols.Bootstrapprovides .iconprev
and .iconnext asplainunicodealternatives.

Optionalcaptions
Addcaptionstoyourslideseasilywiththe .carouselcaption elementwithinany .item .PlacejustaboutanyoptionalHTMLwithinthereanditwillbeautomaticallyalignedand
formatted.

EXA MPLE


900x500

Firstslidelabel
Nullavitaeelitlibero,apharetraauguemollisinterdum.

http://getbootstrap.com/javascript/#collapseexample 44/53
17/2/2017 JavaScriptBootstrap
<divclass="item">
<imgsrc="..."alt="...">
<divclass="carouselcaption">
<h3>...</h3>
<p>...</p>
</div>
</div>

Usage
Multiplecarousels
Carouselsrequiretheuseofan id ontheoutermostcontainer(the .carousel )forcarouselcontrolstofunctionproperly.Whenaddingmultiplecarousels,orwhenchanginga
carousel's id ,besuretoupdatetherelevantcontrols.

Viadataattributes
Usedataattributestoeasilycontrolthepositionofthecarousel. dataslide acceptsthekeywords prev or next ,whichalterstheslidepositionrelativetoitscurrentposition.
Alternatively,use dataslideto topassarawslideindextothecarousel dataslideto="2" ,whichshiftstheslidepositiontoaparticularindexbeginningwith 0 .

The dataride="carousel" attributeisusedtomarkacarouselasanimatingstartingatpageload.Itcannotbeusedincombinationwith(redundantandunnecessary)


explicitJavaScriptinitializationofthesamecarousel.

ViaJavaScript
Callcarouselmanuallywith:

$('.carousel').carousel()

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

Name type default description

interval number 5000 Theamountoftimetodelaybetweenautomaticallycyclinganitem.Iffalse,carouselwillnotautomaticallycycle.

pause string|null "hover" Ifsetto "hover" ,pausesthecyclingofthecarouselon mouseenter andresumesthecyclingofthecarouselon mouseleave .Ifsetto
null ,hoveringoverthecarouselwon'tpauseit.

wrap boolean true Whetherthecarouselshouldcyclecontinuouslyorhavehardstops.

keyboard boolean true Whetherthecarouselshouldreacttokeyboardevents.

Methods
http://getbootstrap.com/javascript/#collapseexample 45/53
17/2/2017 JavaScriptBootstrap

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.

Events
Bootstrap'scarouselclassexposestwoeventsforhookingintocarouselfunctionality.

Botheventshavethefollowingadditionalproperties:

direction :Thedirectioninwhichthecarouselissliding(either "left" or "right" ).


relatedTarget :TheDOMelementthatisbeingslidintoplaceastheactiveitem.

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

EventType Description

slide.bs.carousel Thiseventfiresimmediatelywhenthe slide instancemethodisinvoked.

slid.bs.carousel Thiseventisfiredwhenthecarouselhascompleteditsslidetransition.

$('#myCarousel').on('slide.bs.carousel',function(){
//dosomething
})

http://getbootstrap.com/javascript/#collapseexample 46/53
17/2/2017 JavaScriptBootstrap

Affixaffix.js
Example
Theaffixplugintoggles position:fixed; onandoff,emulatingtheeffectfoundwith position:sticky; .Thesubnavigationontherightisalivedemooftheaffixplugin.

Usage
UsetheaffixpluginviadataattributesormanuallywithyourownJavaScript.Inbothsituations,youmustprovideCSSforthepositioningandwidthofyouraffixedcontent.

Note:Donotusetheaffixpluginonanelementcontainedinarelativelypositionedelement,suchasapulledorpushedcolumn,duetoaSafarirenderingbug.

PositioningviaCSS
Theaffixplugintogglesbetweenthreeclasses,eachrepresentingaparticularstate: .affix , .affixtop ,and .affixbottom .Youmustprovidethestyles,withtheexceptionof
position:fixed; on .affix ,fortheseclassesyourself(independentofthisplugin)tohandletheactualpositions.

Here'showtheaffixpluginworks:

1.Tostart,thepluginadds .affixtop toindicatetheelementisinitstopmostposition.AtthispointnoCSSpositioningisrequired.


2.Scrollingpasttheelementyouwantaffixedshouldtriggertheactualaffixing.Thisiswhere .affix replaces .affixtop andsets position:fixed; (providedby
Bootstrap'sCSS).
3.Ifabottomoffsetisdefined,scrollingpastitshouldreplace .affix with .affixbottom .Sinceoffsetsareoptional,settingonerequiresyoutosettheappropriateCSS.In
thiscase,add position:absolute; whennecessary.ThepluginusesthedataattributeorJavaScriptoptiontodeterminewheretopositiontheelementfromthere.

FollowtheabovestepstosetyourCSSforeitheroftheusageoptionsbelow.

Viadataattributes
Toeasilyaddaffixbehaviortoanyelement,justadd dataspy="affix" totheelementyouwanttospyon.Useoffsetstodefinewhentotogglethepinningofanelement.

<divdataspy="affix"dataoffsettop="60"dataoffsetbottom="200">
...
</div>

ViaJavaScript
CalltheaffixpluginviaJavaScript:

http://getbootstrap.com/javascript/#collapseexample 47/53
17/2/2017 JavaScriptBootstrap

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

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

Name type default description

offset number| 10 Pixelstooffsetfromscreenwhencalculatingpositionofscroll.Ifasinglenumberisprovided,theoffsetwillbeappliedinbothtopand


function| bottomdirections.Toprovideaunique,bottomandtopoffsetjustprovideanobject offset:{top:10} or offset:{top:10,
object bottom:5} .Useafunctionwhenyouneedtodynamicallycalculateanoffset.

target selector| the Specifiesthetargetelementoftheaffix.


node| window
jQuery object
element

Methods
.affix(options)
Activatesyourcontentasaffixedcontent.Acceptsanoptionaloptions object .

$('#myAffix').affix({
offset:15
})

.affix('checkPosition')
Recalculatesthestateoftheaffixbasedonthedimensions,position,andscrollpositionoftherelevantelements.The .affix , .affixtop ,and .affixbottom classesareadded
toorremovedfromtheaffixedcontentaccordingtothenewstate.Thismethodneedstobecalledwheneverthedimensionsoftheaffixedcontentorthetargetelementare
changed,toensurecorrectpositioningoftheaffixedcontent.

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

Events
http://getbootstrap.com/javascript/#collapseexample 48/53
17/2/2017 JavaScriptBootstrap

Bootstrap'saffixpluginexposesafeweventsforhookingintoaffixfunctionality.

EventType Description

affix.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixed.

affixed.bs.affix Thiseventisfiredaftertheelementhasbeenaffixed.

affixtop.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixedtop.

affixedtop.bs.affix Thiseventisfiredaftertheelementhasbeenaffixedtop.

affixbottom.bs.affix Thiseventfiresimmediatelybeforetheelementhasbeenaffixedbottom.

affixedbottom.bs.affix Thiseventisfiredaftertheelementhasbeenaffixedbottom.

GitHub Twitter Examples About

Designedandbuiltwithalltheloveintheworldby@mdoand@fat.Maintainedbythecoreteamwiththehelpofourcontributors.

CodelicensedMIT,docsCCBY3.0.

http://getbootstrap.com/javascript/#collapseexample 49/53
17/2/2017 JavaScriptBootstrap

http://getbootstrap.com/javascript/#collapseexample 50/53
17/2/2017 JavaScriptBootstrap

http://getbootstrap.com/javascript/#collapseexample 51/53
17/2/2017 JavaScriptBootstrap

http://getbootstrap.com/javascript/#collapseexample 52/53
17/2/2017 JavaScriptBootstrap

http://getbootstrap.com/javascript/#collapseexample 53/53

You might also like