Skip to content

Latest commit

 

History

History
1156 lines (862 loc) · 36.5 KB

ch04.asciidoc

File metadata and controls

1156 lines (862 loc) · 36.5 KB

Javascript

Most of the componants discussed in the previous chapter are just the beginning. Bootstrap comes bundled with 13 jQuery plugins that that extend the features, and can add more interaction to your site. To get started with the Bootstrap Javascript plugins, you don’t need to be an advanced Javascript developer. In fact, most of the plugins can be enacted without writing a single line of code by utilizing the Bootstrap data API.

Overview

Bootstrap cand be included on your site in two forms, either compiled or raw. Bootstrap 2.2.2 the uncompressed file is 59kb, and the minimized version is only 32kb. All of the Bootstrap plugins are accessible entirely using the included data API, with this, you don’t need to include a single line of javascript to invoke any of the plugins features.

Typically, Javascript lies in a either a seperate file, or at the bottom of the page before the closing </body> tag. You can either use the src atttribute to link to another file, or write the contents of the file between the opening and closing tags.

Javascript Usage
<!-- To reference another Javascript file -->
<script src="assets/js/javascript.js"></script>

<!-- To write Javascript to the page -->
<script type="text/javascript">
	function js_alert{
		alert('Page has loaded');
	}
</script>

Generally, it is best to include all Javascript calls into check that ensures that the DOM has been loaded on the page. As the browser parses the page, if you have the Javascript trying to fire earlier, it may miss elements. With jQuery, this is easily done by selecting the document, or the entire content of the page, an then applying the .ready() method.

jQuery Ready Method
$(document).ready(function(){
	alert('Page has loaded');
	// Once the page has loaded, and is ready, an alert will fire.
});

Like I mentioned above, Bootstrap has a data API where you can write data attributes into the HTML of the page. If you need to turn off the data API, you can unbind the attributes by adding this line of Javascript.

Disable Bootstrap Javascript Data API
$('body').off('.data-api')

If you need to disable a single plugin, you can do it programmatically using the namespace of the plugin along with the data-api namespace.

Disable an Individual Plugin
$('body').off('.alert.data-api')

Programattic API

The devlelopers of Bootstrap believe that you should be able to use all of the plugins entirely throught the Javascript API. All public APIs are single, chainable methods, and return the collection acted upon.

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

All methods should accept an optional options object, a string which targets a particular method, or nothing (which initiates a plugin with default behavior).

$("#myModal").modal()						// initialized with defaults
$("#myModal").modal({ keyboard: false })	// initialized with no keyboard
$("#myModal").modal('show')					// initializes and invokes show immediately

Transitions

The transition plugin provides simple transition effects. A few examples include:

  • Sliding or fading in modals

  • Fading out tabs

  • Fading out alerts

  • Sliding carousel panes

Modal

A modal is a child window that layered over its parent window. Typically, the point is to display content from a separate source that can have some interaction without leaving the parent window. They can provide information, interaction, or more for a page.. I have used that as a window for holding slideshows, login/registration information, and more. The Modal plugins is probably one of my favorite Bootstrap features.

To create a static example, use the code below.

modal
Figure 1. Static Modal Window
Static Modal Window Code Example
<div class="modal hide fade">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
		<h3>Modal header</h3>
	</div>
	<div class="modal-body">
		<p>One fine body…</p>
	</div>
	<div class="modal-footer">
		<a href="#" class="btn">Close</a>
		<a href="#" class="btn btn-primary">Save changes</a>
	</div>
</div>

To invoke the modal window, you need to have some kind of a trigger. Normally I use a button or an link. If you look in the code below, you will see that the <a> tag, the href="myModal" is the target of the modal that you want to load on the page. The allows you to create multiple modals on the page, and then have different triggers for each of them. Now, to be clear, you don’t load multiple modals at the same time, but can create many on the page to be loaded at different times.

There are three classes to take note of in the modal. The first is modal. This should make sense, but this is identifying the content of the div as a modal. The second is hide. This tells the browser to hide the content of the div until we are ready to invoke it. And last, the fade class. When the modal is toggled, it will cause the content to fade in and out.

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
		<h3 id="myModalLabel">Modal header</h3>
	</div>
	<div class="modal-body">
		<p>One fine body…</p>
	</div>
	<div class="modal-footer">
		<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
		<button class="btn btn-primary">Save changes</button>
	</div>
</div>

Using Modal through Data Attributes

Using the Bootstrap Javascript Data API, you simply need to pass a few data attributes to toggle the slideshow. To start with, set data-toggle="modal" on the link or button that you want to use to invoke the modal and then data-target="#foo" to the ID of the modal that you’d like to use.

Using Modal through Javascript

To call a modal with id="myModal" use a single line of JavaScript:

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

Modal Options

Options can either be passed in via data attributes, or with Javascript. To use the data attributes, prepend data- to the option name, like, data-backdrop="".

Table 1. Modal Options
Name Type Default Description

backdrop

boolean

true

Set to flase if you don’t want the modal to be closed when they click outside of the modal.

keyboard

boolean

true

Closes the modal when escape key is pressed, set to false to disable.

show

boolean

true

Shows the modal when initialized.

remote

path

false

Using the jQuery .load method, inject content into the modal body. If an href with a valid URL is added, that will load that content.

Methods

Options

Activates your content as a modal. Accepts an optional options object.

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

Manually toggles a modal.

.modal('toggle')
$('#myModal').modal('toggle')
Show

Manually opens a modal.

.modal('show')
$('#myModal').modal('show')
Hide

Manually hides a modal.

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

Events

If you need specific events during the firing events of Bootstrap’s modals, you can use the folloing events.

Table 2. Modal Events
Event Description

show

Fired after the show method is called.

shown

Fired when the modal has been made visible to the user.

hide

Fired when the hide instance method has been called.

hidden

Fired when the modal has finished being hidden from the user.

$('#myModal').on('hidden', function () {
	 alert('Hey girl, I heard you like modals...');
})

Dropdown

The dropdown was covered extensively in chapter 3, but then, the interaction was simply glossed over. As a refresher, dropdowns can be added to the the navbar, pills, tabs and buttons.

Dropdown Usage via the Data API

To use, add use data-toggle="dropdown" to a link or button to toggle the dropdown.

dropdown javascript
Figure 2. Dropdown Within Navbar
Dropdown Code Example with Data Attributes
<li class="dropdown">
	<a href="#" id="drop" role="button" class="dropdown-toggle" data-toggle="dropdown">Word <b class="caret"></b></a>
	<ul class="dropdown-menu" role="menu" aria-labelledby="drop">
		<li><a tabindex="-1" href="#">MAKE magazine</a></li>
		<li><a tabindex="-1" href="#">WordPress DevelopmentS</a></li>
		<li><a tabindex="-1" href="#">Speaking Engagements</a></li>
		<li class="divider"></li>
		<li><a tabindex="-1" href="#">Social Media</a></li>
	</ul>
</li>

If you need to keep links entact, useful if the browser is not enabling Javascript, use the data-target attribute along with href="#".

Dropdown via the data-target Attribute
<div class="dropdown">
	<a class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="/page.html">
		Dropdown
		<b class="caret"></b>
	</a>
	<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
		...
	</ul>
</div>

Dropdown Usage via Javascript

To call the dropdown toggle via Javascript, use the following method.

Dropdown via Javascript
$('.dropdown-toggle').dropdown()

Methods

The dropdown toggle has a simple method to show or hide the dropdown. There are no options.

$().dropdown('toggle')

Scrollspy

The scrollspy plugin allows you to target sections of the page based on scroll position. In its basic implementation, as you scroll you can add active classes to the nav bar based on the scroll postion. To add the scrollspy plugin via data attributes, add data-spy="scroll" to the element you want to spy on (most typically this would be the body) and data-target=".navbar" to the navbar that you want to apply the class changes to. For this to work, you must have elements in the body of the page that have matching ids of the links that you are spying on.

scrollspy

Usage

Body Configuration for Scrollspy
<body data-spy="scroll" data-target=".navbar">...</body>

In the navbar, you will need to have page anchors that will serve as indicators for the element to spy on.

Navbar Setup for Scrollspy
<div class="navbar">
	<div class="navbar-inner">
		<div class="container">
			<a class="brand" href="#">Jake's BBQ</a>
			<div class="nav-collapse">
				<ul class="nav">
					<li class="active"><a href="#">Home</a></li>
					<li><a href="#pork">Pork</a></li>
					<li><a href="#beef">Beef</a></li>
					<li><a href="#chicken">Chicken</a></li>
				</ul>
			</div><!-- /.nav-collapse -->
		</div>
	</div><!-- /navbar-inner -->
</div>
Usage via Javascript
Javascript Usage
$('#navbar').scrollspy()

Scrollspy Methods

.scrollspy('refresh')

When calling the scrollspy via the Javascript method, you will need to call the .refresh method to update the DOM. This is helpful if any elements of the DOM have changed.

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

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-offset="".

Table 3. Scrollspy Options
Name type default description

offset

number

10

Pixels to offset from top of page when calculating position of scroll.

The offset option is handy when you are using a fixed navbar. You will want to offset the scroll by about 50 pixels so that it reads at the correct time.

Events

Event Description

activate

This event fires whenever a new item becomes activated by the scrollspy.

Toggleable Tabs

That tabbable tabs were introduced back in chapter 3. Combing a few data attributes, you can easily create a tabbed interface. To do so, create the nav interface, and then wrap the content of the tabs inside a <div> with a class of .tab-content.

toggleable tabs
Figure 3. Toggleable Tabs
Basic Markup of Toggleable Tabs
<ul class="nav nav-tabs">
	<li><a href="#home" data-toggle="tab">Home</a></li>
	<li><a href="#profile" data-toggle="tab">Profile</a></li>
	<li><a href="#messages" data-toggle="tab">Messages</a></li>
	<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>

<div class="tab-content">
	<div class="tab-pane active" id="home">...</div>
	<div class="tab-pane" id="profile">...</div>
	<div class="tab-pane" id="messages">...</div>
	<div class="tab-pane" id="settings">...</div>
</div>

Usage

To enable the tabs, you can use the Bootstrap Data API, or using Javascript directly. With the Data API, you need to add data-toggle to the anchors. The anchor targets will activate the the element that has the .tab-pane class and relative ID. Alternatively, data-target="" may be used instead of href="#" to apply the same action.

Enable Tabs via Javascript
 $('#myTab a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
})
Example of different ways to activate tabs
$('#myTab a[href="#profile"]').tab('show'); // Select tab by name
$('#myTab a:first').tab('show'); // Select first tab
$('#myTab a:last').tab('show'); // Select last tab
$('#myTab li:eq(2) a').tab('show'); // Select third tab (0-indexed)

Events

Event Description

show

This event fires on tab show, but before the new tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.

shown

This event fires on tab show after a tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.

Example of shown method
$('a[data-toggle="tab"]').on('shown', function (e) {
	e.target // activated tab
	e.relatedTarget // previous tab
})

For more information about the jQuery .on method, read more at the jQuery website. jQuery .on

Tooltips

Tooltips are useful when you need to describe a link, or perphaps used in conjuction with the <abbr> tag, provide the defintion of an abbreviation. The plugin was originally based on the jQuery.tipsy plugin written by Jason Frame. It has since been updated to work without images, animate with a CSS animation, and work with the Bootstrap Javascript API.

tooltips
Figure 4. Tooltip Placement

Usage

Bootstrap Data API
<a href="#" rel="tooltip" title="This is the tooltip">Tooltip Example</a>
Javasscript
$('#example').tooltip(options)

Options

Like all of the plugins, there are options that can be added via the Bootstrap Data API, or invoked via Javascript. All options need to have have data- appended to them. So, the title option would become data-title.

Name type default description

animation

boolean

true

apply a css fade transition to the tooltip

html

boolean

false

Insert html into the tooltip. If false, jquery’s text method will be used to insert content into the dom. Use text if you’re worried about XSS attacks.

placement

string/function

\'top\'

how to position the tooltip - top/bottom/left/right

selector

string

false

If a selector is provided, tooltip objects will be delegated to the specified targets.

title

string/function

''

default title value if title tag isn’t present

trigger

string

\'hover\'

how tooltip is triggered - click

hover

focus

manual

delay

Methods

Options

Attaches a tooltip handler to an element collection.

$().tooltip(options)

Show

Reveals an element’s tooltip.

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

Hides an element’s tooltip.

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

Toggles an element’s tooltip.

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

Hides and destroys an element’s tooltip.

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

Popover

The popover is a sibling of the tooltip, offering an entended view, complete with a heading. For the popver to activate, a person just needs to hover over the element. The content of the popver can be populated entirely using the Bootstrap Data API. This method required tooltip.

popover
Figure 5. Popover Placement
<a href="#" class="btn" rel="popover" title="Using Popover" data-content="Just add content to the data-content attribute.">Click Me!</a>

Usage

Enable with Javascript
$('#example').popover(options)

Options

All options can be passed via the Boostrap Data API, or directly with Javascript.

Name type default description
animation boolean true apply a css fade transition to the tooltip
html boolean false Insert html into the popover. If false, jquery's text method will be used to insert content into the dom. Use text if you're worried about XSS attacks.
placement string|function 'right' how to position the popover - top | bottom | left | right
selector string false if a selector is provided, tooltip objects will be delegated to the specified targets
trigger string 'click' how popover is triggered - click | hover | focus | manual
title string | function '' default title value if `title` attribute isn't present
content string | function '' default content value if `data-content` attribute isn't present
delay number | object 0 delay showing and hiding the popover (ms) - does not apply to manual trigger type If a number is supplied, delay is applied to both hide/show Object structure is: delay: { show: 500, hide: 100 }

Methods

Options

Initializes popovers for an element collection.

$().popover(options)
Show

Reveals an elements popover.

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

Hides an elements popover.

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

Toggles an elements popover.

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

Hides and destroys an element’s popover.

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

Alerts

With the Data APi, it is easy to add dismiss functionality to alert messages.

alert error

Usage

Dismiss Via Javascript
$(".alert").alert()
Dismiss Via Data API
<a class="close" data-dismiss="alert" href="#">&times;</a>

Methods

$().alert()

To enable all alerts to be ale to be closed, add the above method. To enable alerts to animate out when closed, make sure they have the .fade and .in class already applied to them.

Close

Closes an alert.

$(".alert").alert('close')

Events

There are two event that can be tied to Bootstrap’s alert class.

Event Description

close

This event fires immediately when the close instance method is called.

closed

This event is fired when the alert has been closed (will wait for css transitions to complete).

$('#my-alert').bind('closed', function () {
  // do something…
})

Buttons

Buttons were introduced in chapter 3, and you don’t need to do anything to make them work as links, and as buttons in forms. There is some additional interaction that you can add with the plugin, notably loading states, and adding toolbar like functionality to button groups.

Loading State

To add a loading state to a button, simply add data-loading-text="Loading…​" as an attribute to the button. When the button is clicked, the .disabled class is added, giving the apearence that it can no longer be clicked.

button loading
Figure 6. Loading Button
<button type="button" class="btn btn-primary" data-loading-text="Loading...">Submit!</button>

Single Toggle

When clicking on a button with the data-toggle="button" attribute, a class of .active is added.

button toggle
Figure 7. Toggle Button
<button type="button" class="btn btn-primary" data-toggle="button">Toggle</button>

Checkbox Buttons

Buttons can work like checkboxes, where you can select many of the options in a button group. To add this function, add data-toggle="buttons-checkbox" for checkbox style toggling on btn-group.

button checkbox
Figure 8. Checkbox Buttons
<div class="btn-group" data-toggle="buttons-checkbox">
  <button type="button" class="btn btn-primary">Left</button>
  <button type="button" class="btn btn-primary">Middle</button>
  <button type="button" class="btn btn-primary">Right</button>
</div>

Radio Buttons

Radio buttons function similarily to checkboxes, the primary difference is that a radio button doesn’t allow for multiple selections, only one in the group. To add this function, add data-toggle="buttons-radio" for radio style toggling on btn-group.

button radio
Figure 9. Radio Buttons
<div class="btn-group" data-toggle="buttons-radio">
  <button type="button" class="btn btn-primary">Left</button>
  <button type="button" class="btn btn-primary">Middle</button>
  <button type="button" class="btn btn-primary">Right</button>
</div>

Usage

The .button method can be applied to any class or ID that you want. To enable all buttons in the .nav-tabs via Javascript, add this code:

$('.nav-tabs').button()

Methods

Toggle

Toggles push state. Gives the button the appearance that it has been activated.

$().button('toggle')
Loading

Sets button state to loading - disables button and swaps text to loading text. Loading text should be defined on the button element using the data attribute data-loading-text.

<button type="button" class="btn" data-loading-text="loading stuff..." >...</button>
Reset

Resets button state, bringing the original content back to the text. Useful when you need to return the button back to the primary state.

$().button('reset')
String

String in this method is referring to any string decalred by the user.

$().button('string')

To reset the button state, and bring in new content, use the string method.

<button type="button" class="btn" data-complete-text="finished!" >...</button>

<script>
  $('.btn').button('complete')
</script>

Collapse

The collapse plugin makes it easy to make collapsing divs. Whether you use it to build accordian naviation or content boxes, it allows for a lot of content options.

collapse
Figure 10. Example Accordian
Accordian Code
<div class="accordion" id="accordion2">
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
        Collapsible Group Item #1
      </a>
    </div>
    <div id="collapseOne" class="accordion-body collapse in">
      <div class="accordion-inner">
        Anim pariatur cliche...
      </div>
    </div>
  </div>
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
        Collapsible Group Item #2
      </a>
    </div>
    <div id="collapseTwo" class="accordion-body collapse">
      <div class="accordion-inner">
        Anim pariatur cliche...
      </div>
    </div>
  </div>
</div>
...

You can also use the data attributes to make all content collapsable.

<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#demo">
  simple collapsible
</button>

<div id="demo" class="collapse in"></div>

Usage

Via Data Attributes

Like all of the plugins that use the data attributes API, you can add all needed markup without writing any Javascript. Add data-toggle="collapse" and a data-target to the element to automatically assign control of a collapsible element. The data-target attribute will accept a css selector to apply the collapse to. Be sure to add the class .collapse to the collapsible element. If you’d like it to default open, add the additional class .in.

To add accordion-like group management to a collapsible control, add the data attribute data-parent="#selector".

Via Javascript
$(".collapse").collapse()

Options

Options can be passed via data attributes, or with Javascript.

Name type default description

parent

selector

false

If selector then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior)

toggle

boolean

true

Toggles the collapsible element on invocation

Methods

Options

Activates your content as a collapsible element. Accepts an optional options object.

.collapse(options)
Toggle

Toggles a collapsible element to shown or hidden.

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

Shows a collapsible element.

.collapse('show')
Hide

Hides a collapsible element.

.collapse('hide')

Events

There are four events that can be hooked into with the collapse plugin.

Event Description

show

This event fires immediately when the show instance method is called.

shown

This event is fired when a collapse element has been made visible to the user (will wait for css transitions to complete).

hide

This event is fired immediately when the hide method has been called.

hidden

This event is fired when a collapse element has been hidden from the user (will wait for css transitions to complete).

$('#myCollapsible').on('hidden', function () {
  // do something…
})

The Bootstrap carousel is a flexible, responsive way to add a slider to your site. In addiotn to being responsive, the content is flexible enough to allow images, iframes, video, or likely anytime of content that you might want.

carousel
Figure 11. Carousel Example
Carousel Code Example
<div id="myCarousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <div class="active item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <!-- Carousel nav -->
  <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a>
  <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a>
</div>

Usage

To implement the carousel, you just need to add the code with the markup above. No need for data atrributes, just simple class based development. To call the carousel with Javascript, you can do it manually with the following code:

$('.carousel').carousel()

Options

Options can be passed through data attributes, or through Javascript.

Name type default description

interval

number

5000

The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.

pause

string

"hover"

Pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.

Methods

Options

Initializes the carousel with an optional options object and starts cycling through items.

$('.carousel').carousel({
  interval: 2000
})
Cycle

Cycles through the carousel items from left to right.

.carousel('cycle')
Pause

Stops the carousel from cycling through items.

.carousel('pause')
Number

Cycles the carousel to a particular frame (0 based, similar to an array).

.carousel(number)
Prev

Cycles to the previous item.

.carousel('prev')
Next

Cycles to the next item.

.carousel('next')

Events

The carousel has two events that you can hook into.

Event Description

slide

This event fires immediately when the slide instance method is invoked.

slid

This event is fired when the carousel has completed its slide transition.

Typeahead

Typeahead allows you to easily create typeahead inputs in forms. Example, you could preload states in a state field, or using some Javascript, get search results using some ajax calls.

typeahead
Figure 12. Typeahead Example

Usage

Using data API, you can add sources via the data-source attribute. Items should be listed in either a JSON array, or a function.

Typeahead Code Example
<input
	type="text"
	class="span3"
	data-provide="typeahead"
	data-items="4"
	data-source="[
		'Alabama',
		'Alaska',
		'Arizona',
		'Arkansas',
		'California',
		...
		]"
>

To call directly with Javascript, use the following method.

Javscipt Method
$('.typeahead').typeahead()

Options

Name type default description

source

array, function

[ ]

The data source to query against. May be an array of strings or a function. The function is passed two arguments, the query value in the input field and the process callback. The function may be used synchronously by returning the data source directly or asynchronously via the process callback’s single argument.

items

number

8

The max number of items to display in the dropdown.

minLength

number

1

The minimum character length needed before triggering autocomplete suggestions

matcher

function

case insensitive

The method used to determine if a query matches an item. Accepts a single argument, the item against which to test the query. Access the current query with this.query. Return a boolean true if query is a match.

sorter

function

exact match, case sensitive, case insensitive

Method used to sort autocomplete results. Accepts a single argument items and has the scope of the typeahead instance. Reference the current query with this.query.

updater

function

returns selected item

The method used to return selected item. Accepts a single argument, the item and has the scope of the typeahead instance.

highlighter

function

highlights all default matches

Method used to highlight autocomplete results. Accepts a single argument item and has the scope of the typeahead instance. Should return html.

Affix

The affix plugin allows you to allow a div to become affixed to a location on the page. A common example of this is social icons on a page. They will start in a location, but as the page hits a certain mark, the div will become locked in place and will stop scrolling with the rest of the page.

Usage

To apply the affix plugin to a div, you can use either data attributes, or use Javascript directly. Of note, you must position the element so that it can be affixed to the page. Position is controlled by the data-spy attribute, using either affix, affix-top, or affix-bottom. You then use the data-offset to calcualte the position of the scroll.

<div data-spy="affix" data-offset-top="200">
	...
</div>

Options

Name type default description

offset

number/function/object

10

Pixels to offset from screen when calculating position of scroll. If a single number is provided, the offset will be applied in both top and left directions. To listen for a single direction, or multiple unique offsets, just provide an object offset: { x: 10 }. Use a function when you need to dynamically provide an offset (useful for some responsive designs).