View on GitHub

Sco.js

A twitter bootstrap javascript extension

Download this project as a .zip file Download this project as a tar.gz file

Why?

The reason for creating sco.js was to improve the existing bootstrap js components and to provide specific use-cases for the projects I was working on. The bootstrap js plugins are great for general stuff but whenever you want something more in-depth or a specific behaviour, they fall short. Most of the bootstrap js plugins are not very extensible (or they were not when I created my version of the plugins) and where they are, my requirements were too different to just extend with 1-2 lines of code. This is not to say bootstrap and its js components are bad! It's a really good framework for rapid development but...1 size doesn't fit all. In my case it almost fit ;)

Note: bootstrap is using css transitions where possible and this is a great thing! Only a few of my plugins are using transitions but I am working on adding them wherever possible.

What you get

All plugins in sco.js can be used on a bootstrap-enabled site but they can be used separately as well. Also, sco.js contains plugins that are not available in bootstrap. Plugins are unit tested and in use on production sites. Each plugin can be enabled and configured via data-attributes data-trigger="pluginName" or programatically var $modal = $.scojs_modal({...}). Each plugin has a "reason for being" (see below) - what it tries to achieve, what it does differently from bootstrap, why I created it in the first place.

In most cases the css comes from bootstrap. I also tried to follow the bootstrap docs, formatting and conventions as much as possible so users of bootstrap would feel right at home with sco.js

When data attributes are available to trigger a specific plugin, the attribute to use is data-trigger="plugin name" to not conflict with bootstrap's data-toggle="plugin name". This way you can use both bootstrap and sco.js freely and interchangeable.

What's next?

  • Like mentioned in the note above, one of the priorities is to get css transition support working wherever possible.
  • Carousel is coming too, based on panes.
  • Ajax support for panes (and automatically for tab and carousel) - you should be able to load remote content into a pane or more slides into a carousel.
  • Add predelay to tooltip - for when you might want the tooltip to appear after a bit of delay.
  • ARIA support for form validation.
  • If enough interest, I will update the form validation to make use of data-* attributes and make it more extensible, otherwise this is a low priority for now.
  • Other suggestions?

What?

The primary use of the modal is to load remote content (loaded via ajax) and display that in an overlay, on top of the current page. It can also be used to display something without loading it but it's not its primary use case.

Why?

Because bootstrap modals didn't allow remote content when I created this. Also, I didn't want to clutter every page where I might use a modal with the modal content / HTML markup. The Sco.js modal requires nothing more than a link on the page.

Lets say we have a site eg. a hotel, and each room has a booking form, rather than clutter up every page with the same booking form html we would put the form in a separate html file eg. "my-booking-form.html" and when calling the modal use href="my-booking-form.html" to ajax in that content and keep our main content uncluttered and seo friendly.

Dependencies

The modal does not depend on other libraries (other than jQuery, of course). However, we recommend you load spin.js. If spin.js is found, a spinning wheel is displayed during the loading of remote content.

Examples

<!-- Button to trigger modal -->
<a data-trigger="modal" href="lipsum.html" data-title="Modal title" class="btn">Launch demo modal</a>

You don't need to worry about providing any HTML structure to the modal, this is done automatically for you. The default markup is listed in the Options section and the css comes from bootstrap. All you need to provide is the modal title and the url to the remote content. However, if you need to specify your own HTML markup check the target option.

Usage

Via data attributes (data-api)

Look ma', no js code:

<button type="button" data-trigger="modal">Launch modal</button>

All plugin options are available to use as data attributes. The data-api usage is "live" - meaning that you don't have to rebind new elements. Every new element having a data-trigger="modal" attribute that is added to the dom after the initial load will work out of the box.

As a jquery plugin

$('#trigger').scojs_modal(options);
or
$('.modal_triggers').scojs_modal(options);

If the trigger element has data- attributes and you pass options as well, the data attributes overwrite the options with the same name.

This part is quite different from bootstrap's implementation. In bootstrap, the selected element should be the modal (meaning the modal HTML should already exist in the dom). It also means the modal HTML cannot be reused by other modals (i.e. if you want more modals on the page, each has to have its own id/html code).
In our case, the selected element is the trigger of the modal (what you click on to launch the modal) and the modal is built based on the trigger's options. You definitely have the option to use different modals but, by default, the same modal HTML is reused by every modal instance on the page. This decision was made because we found out that we never wanted more modals appearing on the page at the same time. So reusing the same modal HTML for every triggered modal seemed quite logical.

With access to the object

var modal = $.scojs_modal(options);

This gives you access to the created javascript object. Note that when you launch the modal this way, it's not shown by default. You'll have to call modal.show() at a later time to show the modal.

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

Name type default description
title string &nbsp; The title of the modal.
target string #modal The modal ID. If an HTML element with this ID already exists in the DOM, the modal content will be placed inside that, otherwise a standard HTML modal structure will be created automatically. The default structure is:
<div class="modal fade" id="modal">
  <div class="modal-header">
    <a class="close" href="#" data-dismiss="modal">×</a>
    <h3> </h3>
  </div>
  <div class="inner"></div>
</div>
The modal is looking for an .inner element inside the target to place the content there so if using your own HTML markup, make sure you have an .inner element.
remote string The remote url to load content from. If the trigger element is an <a> and the data-api is used the href attribute is used for the remote option. If no href attribute exists or if it is empty or '#', the option is ignored.
content string Use this to define the modal content when you don't want to load the content remotely. Use either this option or the remote one but not both at once. You could use it like
$('#trigger').scojs_modal({content: 'Lorem ipsum...'});
or
$('#trigger').scojs_modal({content: $('#other').html()});
Note that if both the remote and content options are specified, the content is ignored. With the data-api, set the href to an empty string or '#' to have the remote option ignored.
appendTo string body By default, the new modal and backdrop HTML are appended to the body element. Use this option to append them to some other element.
cache boolean false Set this to true if you want to cache the first remote call output and reuse it on subsequent modal triggers. This could be useful for, say, a login modal, when the user triggers the modal, changes her mind, closes the modal then later on opens it again.
keyboard boolean false Closes the modal when the escape key is pressed.
nobackdrop boolean false Does not show the modal-backdrop element if set to true.
cssclass string The css class(es) to add to modal.
width int The modal width. This will be set inline on the .modal element. You should use the cssclass to add css that sets the width instead of this option.
height int The modal height. This will be set inline on the .modal element. You should use the cssclass to add css that sets the height instead of this option.
left int The modal left position. This will be set inline on the .modal element. You shouldn't normally have to use this option as the default css centers the modal on screen. Could be used for some sort of on-page help system/guides.
top int The modal top position. This will be set inline on the .modal element. You shouldn't normally have to use this option as the default css centers the modal on screen. Could be used for some sort of on-page help system/guides.
onClose function If set, this function is called after the modal is closed.

.scojs_modal(options)

$('#trigger').scojs_modal({
  title: 'Modals are cool',
  content: "No, they're not"
});

There are no other methods available in data-api or jQuery mode yet. The following methods are available in when you get access to the js object:

.show()

Shows the modal.

var modal = $.scojs_modal({
  keyboard: true
});
modal.show();

.close()

Closes the modal.

var modal = $.scojs_modal({
  keyboard: true
});
modal.show();
modal.close();

.destroy()

Closes and destroys the modal, removes all modal HTML and events from the DOM.

var modal = $.scojs_modal({
  keyboard: true
});
modal.show();
modal.destroy();

What?

A specialised modal that has a yes/no button in the footer. The yes is attached to some action, the no dismisses the modal without doing anything else. Basically a glorified alert().

Why?

We wanted an easy way to make the user confirm some action like deleting something from their profiles.

Dependencies

The confirm plugin depends on the modal. Make sure you load both when you want to use confirm.

Examples

Launch demo confirm

(Note that if you click on yes on the confirmation modal, you will be taken to a non-existing page)

<!-- Button to trigger confirm -->
<a data-trigger="confirm" href="/delete/me" class="btn">Launch demo confirm</a>

Usage

Via data attributes (data-api)

<a href="/link-to-go-to/when-user-presses-yes" data-trigger="confirm">Launch confirm</button>

All modal options are available for confirm as well though some might not make much sense (like loading remote content). There are some extra options available for confirm, see the options below.

As a jquery plugin

$('#confirm_trigger').scojs_confirm(options);

Like with the modal, you call scojs_confirm() on the trigger, not on the modal element itself. And, if data- attributes exist, they overwrite any general options you pass to the plugin.

With access to the object

var confirm = $.scojs_confirm(options);

This gives you access to the created javascript object. Note that when you launch the confirm this way, it's not shown by default. You'll have to call confirm.show() at a later time to show the confirm modal.

Options

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

All modal options are available for confirm as well. Note, however, that the default confirm modal doesn't have a title so setting title has no effect. You can, of course, have your own confirm modal with a title in which case this option will work as expected. There are also some modal options that don't make much sense to be set for confirm like remote and cache but you're free to use them if you need them.

There are some extra options available for confirm or options that have a different default than the modal. See below:

Name type default description
content string Are you sure you want to delete :title? The content of the confirm modal. ":title" is replaced by the title or data-title attribute/option if any of these exist or by the word "this", making the content "Are you sure you want to delete this?" or "Are you sure you want to delete Foo?".
cssclass string confirm_modal This class is added by default to all confirm modals.
target string #confirm_modal The confirm modal ID. If an HTML element with this ID already exists in the DOM, it will be used, otherwise a standard HTML confirm modal structure will be created automatically. The default structure is:
<div class="modal fade confirm_modal" id="confirm_modal">
  <div class="modal-body inner"></div>
  <div class="modal-footer">
    <a class="btn cancel" href="#" data-dismiss="modal">cancel</a>
    <a href="#" class="btn btn-danger" data-action="1">yes</a>
  </div>
</div>
action string / function This option decides what happens when you click the yes button. In data-api, if a data-action="foo" attribute is found, we check if foo is a function and if it is, that function is assigned as the 'yes' function (will be run when clicking on the yes button). If foo is not a function then it is assumed to be an url. If no data-action attribute is found, the action option is set to the href of the trigger so when you click on yes you will be taken to that url.

For example, clicking on one of the following:

<a data-trigger="confirm" href="/delete/me" class="btn">Delete</a>
<button class="btn" data-action="/delete/me" data-trigger="confirm">Delete</button>
would show the confirm modal and when clicking on the yes button there, you'd be taken to /delete/me.

Note that when both href and data-action are found, href is ignored.

When this option is a function, clicking on the yes button would execute that function (in the context of the confirm modal object) and then close the modal.

Methods

.scojs_confirm(options)

$('#trigger').scojs_confirm({
  content: "Ain't that cute?",
  action: "http://google.com"
});
var confirm = $.scojs_confirm({
  content: "Oh, noes, you really want to delete me?",
  action: function() {
    this.close();
  }
});
confirm.show();

All modal methods are available for the confirm as well.

What?

Accordions or show/hide togglers.

Why?

So much markup in bootstrap for their collapse component! And IDs. I hate IDs! While IDs give you a great degree of freedom in what to target (as in I want this button to collapse this far away block across the page), most of the time it's not how an accordion works. You usually want to click on a menu link and expand the block under/above that link. So I made this collapse plugin to address the said issues.

Dependencies

The collapse does not depend on other libraries (other than jQuery, of course).

Examples

In its most basic form, the collapser plugin is nothing more than a simple on/off toggler for another block element. All you need to get started is a trigger with a data-trigger="collapse" attribute and a div inmediately following the trigger with a class of .collapsible. You will probably want that div to be set to display:none (eg. via the bootstrap helper class .hide or with style="display:none").

Click for default behaviour
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lacinia hendrerit purus, in convallis quam ultricies vel. Sed a dui tellus, ut lacinia felis. Duis eget sapien ut dui congue mattis.
<a href="#" data-trigger="collapse">Click for default behaviour</a>
<div class="collapsible hide">
  Lorem ipsum...
</div>

More examples:

Let's spice things up a bit: the accordion behaviour. In this mode, we need to tell each trigger what html element is the parent for the whole accordion:

<div class="sidenav">
  <a href="#" data-trigger="collapse" data-parent=".sidenav" class="active">Menu 1</a>
  <div class="collapsible">
    The quick brown fox jumps over the lazy dog.
  </div>
  <a href="#" data-trigger="collapse" data-parent=".sidenav">Menu 2</a>
  <div class="collapsible" style="display: none">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  </div>
</div>

We can make this even more interesting by adding a "show more / show less" toggle:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Etiam lacinia hendrerit purus, in convallis quam ultricies vel. Sed a dui tellus, ut lacinia felis. Duis eget sapien ut dui congue mattis.
show more
Q: What does the quick brown fox do?
A: The quick brown fox jumps over the lazy dog.
show more
<div>Lorem ipsum...</div>
<div class="collapsible hide">Etiam lacinia...</div>
<a href="#" class="show_more_example">show more</a>

<div>Q: What does the quick brown fox do?</div>
<div class="collapsible hide">A: The quick brown fox jumps over the lazy dog.</div>
<a href="#" class="show_more_example">show more</a>
<script>
  $(document).on('click', '.show_more_example', function(e) {
    $(this).scojs_collapse({
      triggerHtml: {on: 'show less', off: 'show more'}
      ,mode: 'prev'
    });
    return false;
  });
</script>

Usage

Via data attributes (data-api)

<button data-trigger="collapse" class="btn">Click me</button>

The data-api usage is "live" - meaning that you don't have to rebind new elements. Every new element having a data-trigger="collapse" attribute that is added to the dom after the initial load will work out of the box.

As a jquery plugin

$('#collapse_trigger').scojs_collapse(options);

If data- attributes exist, they overwrite any general options you pass to the plugin.

When you call the plugin this way, all it does is toggle the target. To toggle it back you'd call the plugin again. However, it's best used inside a click event (or hover/etc) like this:

<script>
  $(document).on('click', '.collapse_triggers', function(e) {
    $(this).scojs_collapse(options);
    return false;
  });
</script>

With access to the object

var collapse = $.scojs_collapse(options);

This gives you access to the created javascript object. Note that when you launch the collapse this way, it doesn't toggle the target by default. You'll have to call collapse.toggle() at a later time, as many times as you want, to toggle the target on/off.

Options

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

Name type default description
parent string Using this option activates the accordion behaviour. It should be a jQuery selector for the element wrapping the accordion.
target string Use this option to specify the target element to collapse. It should be a jQuery selector for the element you want to collapse. Normally it's not needed as the plugin can figure out which element to collapse by itself.
activeTriggerClass string Class to add to the trigger in active state (when the target element is visible).
triggerHtml object If not null, this should be a hash like {off: 'more', on: 'less'}. This text is set on the trigger. When target is not visible, the off text is shown on the trigger, otherwise the on text is shown.
mode string next Can be either next or prev. Determines where the element to collapse is to be found in relation to the trigger. next means the trigger comes before the collapsible element while prev means trigger is after the element. The plugin is actually searching for a prev/next sibling of the trigger by using the prev(), next() jQuery functions.
collapseSelector string .collapsible The selector for the target element to be toggled.
triggerSelector string [data-trigger="collapse"] This is used by accordion to find all triggers.
ease string slide The effect to use to show/hide the target element. Must be an effect that supports the toggle jQuery functions (like toggleSlide(), toggleFade() or simply toggle()).

Methods

.scojs_collapse(options)

$('#trigger').scojs_collapse({
  parent: '#sidebar',
  mode: 'prev'
});

There are no other methods available in data-api or jQuery mode yet. The following methods are available when you get access to the js object:

.toggle()

Toggles the target element.

var collapse = $.scojs_collapse();
collapse.toggle();

What?

Tab functionality for your pages.

Why?

Like with the other plugins that already exist in bootstrap that I chose to rewrite, my main problem with bootstrap tabs is the complexity of the markup required and the heavy use of IDs. Sco.js tabs are simpler, have some sane defaults but the simplicity comes with a price: it doesn't support dropdown tabs for example. If you need the extra complexity, by all means, use bootstrap tabs.

Dependencies

Panes - because it's the core of the tabs and carousel. If you want history support you should also include jQuery Address. See below for how to use it.

Examples

To start using the tab plugin you need an <ul data-trigger="tab"> for the tab headers and a <div class="pane-wrapper"> immediately following the ul for the tab content. There should be as many li's in the ul as children elements in the .pane-wrapper div. A click on the first tab header would select the first .pane-wrapper child, a click on the nth tab header would select the nth child.

The links in the tab headers don't need a specific href attribute, unless you want history support:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque posuere hendrerit bibendum. Maecenas vel velit quis quam suscipit eleifend scelerisque vitae nisi. Sed eget dui sem, vel pellentesque nibh. Curabitur ut ligula mauris, non suscipit felis. Phasellus venenatis, erat vitae porta mattis, nunc nunc consectetur nibh, et venenatis tellus arcu at augue. Aliquam ultricies egestas diam, at posuere lorem semper ac.

Phasellus at neque mauris. Integer eu massa consectetur lectus posuere fermentum. Mauris vel ante eu purus tempus suscipit. Maecenas rutrum lacus eget odio tempus ac consequat mauris aliquet. Aenean vitae tortor vitae eros accumsan pulvinar eu eget massa. Suspendisse in ligula nec nulla tempus pellentesque. Pellentesque pulvinar lacus ac tortor dictum sit amet molestie dolor mollis.

Duis facilisis ligula sed libero pharetra fermentum. Fusce at odio sapien, vitae eleifend mauris. Nullam vitae nunc non purus aliquet blandit at nec ipsum. Pellentesque at nisi consequat magna venenatis varius non eget nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut facilisis vestibulum risus, id mattis erat condimentum iaculis. Nunc luctus scelerisque arcu a lacinia. Nulla quis magna mauris, id dignissim risus. Mauris neque urna, sollicitudin vitae accumsan a, tincidunt a ipsum.

Praesent mollis scelerisque aliquam. Proin dui lacus, consequat sed pretium sed, vehicula a orci. Duis tristique eros lorem, quis consectetur sapien. Nulla facilisi. Vestibulum luctus, lorem vitae ullamcorper mattis, erat erat venenatis mi, non sodales urna tortor sit amet purus. Pellentesque ut eros a arcu consequat volutpat ac id purus. Integer feugiat accumsan justo, sed ultricies urna ultricies eu. Maecenas commodo adipiscing nulla in feugiat. Nam eu est nunc.

<ul class="nav nav-tabs" data-trigger="tab">
  <li><a href="#">Tab 1</a></li>
  <li><a href="#">Tab 2</a></li>
  <li><a href="#">Tab 3</a></li>
  <li><a href="#">Tab 4</a></li>
</ul>
<div class="pane-wrapper">
  <div>...</div>
  <div>...</div>
  <div>...</div>
  <div>...</div>
</div>

Browser history support

To enable history support for tabs make sure you load jQuery Address and that the links in your tab headers have anchor hrefs (e.g <a href="#foo">Tab 1</a>).
However, the hrefs must NOT point to any element on the page (there should be no element with that ID on the page). The history support is bidirectional:

  • when you click on a tab header that has an anchor href the hash gets added to the current url. This is the easy direction :)
  • when you add the hash of a tab header to the url, the tab switches to that pane

If there's an element that has the same ID as one of your hrefs, the tabs will still function properly but the page will "jump" to that element, as anchors are supposed to work in browser.

Tab 1 content
Tab 2 content
Tab 3 content
Tab 4 content

Click on the tabs above and see how the hash is added to the page url (which is normal browser behaviour) and try adding #tab1 or #tab2 or #tab3 to this page url manually and see how the tabs change. You can also click on the last tab header - the proper pane will be selected but the page will jump up to modals.

Usage

Via data attributes (data-api)

See the examples above for how you can use this with the data-api. You need to add data-trigger="tab" to the element wrapping the tab headers.

The data-api usage is NOT "live", unfortunately. If you add elements to the DOM having a data-trigger="tab" attribute, you will have to also bind that new element yourself using javascript.

As a jquery plugin

$('#mytabs').scojs_tab(options);

If the #mytabs element has data- attributes and you pass options as well, the data attributes overwrite the options with the same name.

With access to the object

var tab = $.scojs_tab('#mytabs', options);

Options

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

Name type default description
content string (required) The selector for the pane wrapper element. The pane wrapper element should have a .pane-wrapper class.
active integer 0 The index of the active tab (0 based).
mode string next Can be either next or prev. Determines where .pane-wrapper is to be found in relation to the headers ul. next means .pane-wrapper comes after (under) the headers while prev means .pane-wrapper is before (above) the element. The plugin is actually searching for a prev/next sibling of the header ul by using the prev(), next() jQuery functions.
easing string The css class to add to the wrapper. You could add the class yourself in html without specifying this option to the plugin but I might implement a javascript fallback for fade/slide so it's better that the plugin is aware of this. At the moment you can use xfade, slide and flip. You can, of course, define your own css-based transition effects, in which case you'd specify here the name of your css class.
For example, you could use easing: 'flip-vertical', copy all styles that start with .pane-wrapper.flip in scojs.css, replace .flip with .flip-vertical there and rotateY with rotateX.
onBeforeSelect function The callback to run just before selecting a new tab. If your callback returns false, the new tab will not be selected. Inside the function, this refers to the tab object so you can access all other tab properties (like this.options, etc).

Methods

.select(index)

Select the index-th element (0-based).

var $tab = $.scojs_tab('#foo');
$tab.select(1);

What?

Y'know...tooltips. The kind of dialog baloon that usually appears on hover over stuff.

Why?

While other tooltip plugins focus on pixel perfect positioning, the main focus of Sco.js tooltips plugin is to keep the actual tooltip in the viewport at all times. It's not so much about perfect positioning but about making sure that it's fully shown in the view area when you hover over elements with tooltips, even over those that are positioned near edges of the viewport.

Dependencies

jQuery.

Examples

<a href="#" data-trigger="tooltip" data-content="Lorem ipsum dolor">Hover me</a>

Scroll the page up till the example link above is at the very top of the page and hover over the link again - you will see the tooltip appearing below the link. Try the same with left/right/bottom - the tooltip will reposition itself to stay on page all the time.

Usage

Via data attributes (data-api)

<div data-trigger="tooltip" data-content-elem="#tooltip_element">Hover me</div>

The data-api usage is "live" - meaning that you don't have to rebind new elements. Every new element having a data-trigger="tooltip" attribute that is added to the dom after the initial load will work out of the box.

As a jquery plugin

$('.tooltips').scojs_tooltip(options);

If the trigger element has data- attributes and you pass options as well, the data attributes overwrite the options with the same name.

With access to the object

var tooltip = $.scojs_tooltip('#trigger', options);

This gives you access to the created javascript object. Note that when you launch the tooltip this way, it's not shown by default. You'll have to call tooltip.show() at a later time to show the tooltip.

Options

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

Name type default description
content string The content that should be shown in the tooltip.
content, contentAttr, contentElem are mutually exclusive, use only one of them.
contentAttr string Get the content from the trigger attribute specified by this option.
content, contentAttr, contentElem are mutually exclusive, use only one of them.
contentElem string Get the content from some other element on the page (this is the selector for that element) $('.tooltip').scojs_tooltip({contentElem: '#foo'}).
content, contentAttr, contentElem are mutually exclusive, use only one of them.
hoverable bool true If this option is set to true, hovering over the tooltip will keep it open. When set to false, only hover over the trigger will keep the tooltip open.
delay int 200 The time in milliseconds after the mouse leaves the trigger element before the tooltip is hidden.
cssclass string If set, this class is added to the tooltip so you can have your own, custom, tooltip style (.tooltip.myclass).
position string n Where should the tooltip be shown in relation to the trigger. Possible values are:
  • e to the left of the trigger
  • w to the right of the trigger
  • n above the trigger
  • s below the trigger
  • ne top right corner of the trigger
  • nw top left corner of the trigger
  • se bottom right corner of the trigger
  • sw bottom left corner of the trigger
  • center centered over the trigger
autoclose bool true When true, the tooltip behaves like any normal tooltip: it's shown on mouse over trigger and hidden on mouse out. When false, the tooltip is shown on mouse over but not hidden anymore on mouse out. You will have to close it either by javascript or have a button/link with a data-dismiss="tooltip" attribute which will close the tooltip on click.
Example:
See the wonder
This is such an important message that you need to click to close
target string When this is set it should be a selector for some other element on the page. The tooltip will be shown over that element instead of over the trigger.
Example:

Methods

.scojs_tooltip(options)

$('#trigger').scojs_tooltip({
  content: "Tooltip content"
  ,cssclass: 'pretty'
  ,delay: 1000
});

The following methods are available when you get access to the js object:

.show()

Shows the tooltip straight away.

var tooltip = $.scojs_tooltip('#trigger', {
  target: '#foo'
  ,content: 'tooltip content'
});
tooltip.show();

.hide()

Hides the tooltip straight away.

var tooltip = $.scojs_tooltip('#trigger', {
  target: '#foo'
  ,content: 'tooltip content'
});
tooltip.show();
tooltip.hide();

.do_mouseenter()

See .do_mouseleave()

.do_mouseleave()

Useful when you have the delay option set and you don't want to hide the tooltip right away but instead hide it after the set delay. Basically, this simulates the mouse leaving the trigger. Also, this gives a chance to the user to hover over the trigger again and keep the tooltip open some more.

var tooltip = $.scojs_tooltip('#trigger', {
  ,delay: 1000
});
tooltip.show();
tooltip.do_mouseleave();  // hides after 1000 seconds

What?

This is a "flash message" - a message that appears at the top of the page and disappears after a few seconds. It can be an info or an error message.

Why?

Useful after some user action (like submitting a form for example) to let them know your app processed the action ok or there was an error.

Dependencies

jQuery.

Examples

Click to see the info message
Click to see the error message
<a id="message_trigger_ok" href="#">Click to see the info message</a>
<a id="message_trigger_err" href="#">Click to see the error message</a>
<script>
  $('#message_trigger_ok').on('click', function(e) {
    e.preventDefault();
    $.scojs_message('This is an info message', $.scojs_message.TYPE_OK);
  });
  $('#message_trigger_err').on('click', function(e) {
    e.preventDefault();
    $.scojs_message('This is an error message', $.scojs_message.TYPE_ERROR);
    });
</script>

Usage

As a jquery plugin

$.scojs_message(message, type);

Where message is the message you want displayed and type should be one of $.scojs_message.TYPE_OK or $.scojs_message.TYPE_ERROR to indicate an error or success message.

Options

Since this is a "singleton" or "static" plugin, options can be changed globally by changing $.scojs_message.<option>

Name type default description
id string page_message The id of the html element that will be used to display the flash message (Note: shouldn't include #). The element is created by the plugin if one doesn't exist.
okClass string page_mess_ok The css class to be added for the success message.
errClass string page_mess_error The css class to be added for the error message.
animate bool true Should the background of the message be animated or not? (some faint stripes moving). Basically it appends the page_mess_animate class or not, depending on the truthiness of this option. Animation is done with CSS3 transitions.
delay integer 4000 For how long to display the message before sliding it off screen.
appendTo string body By default, the new div for the message is appended to the body element. Use this option to append it to some other element.

What?

Valid is a javascript form validation plugin. Basically, you give it a set of rules for a form's fields and it'll either submit the form if all rules pass or show error messages if not.

Valid is the most complex and most opinionated plugin of all sco.js plugins. It also makes extensive use of other plugins (from sco.js and 3rd party) so make sure you load its dependencies before using it. It is loosely based on the jQuery form validation plugin.

Why?

There are a couple of good form validators out there. I built this one because:

  • I needed support for general error messages (i.e. not related to a certain field), besides field-related messages.
  • I needed support for client side validation, as well as server side validation that would pass the errors to the client for display (for example when a field would pass the "must be an email" client-side rule but it won't pass the "email already exists" server-side rule).
  • I wanted support for the JSend format - to pass instructions/messages from the backend to the front end in a standard format.
  • Since I was using the Kohana php framework on the backend, I wanted the validation rules defined there to work transparently on the frontend as well.
  • As much I would have wanted to use the browser form validation API, they were too limited, not translatable and not customizable.

Dependencies

Message to display general messages, jQuery Form Plugin to submit the form via ajax. It uses the JSend specification to receive instructions from the backend. It does not depend on Modal but it knows how to close the modal window if instructed to do so by the backend. The defaults of the plugin are based on the excellent Mosto css framework for forms but you can, of course, customize it to work with any framework.

Examples

<form action="valid.json" id="valid_form" class="form-horizontal">
  <label><div>Email</div> <input type="email" name="email"></label>
  <label><div>Password</div> <input type="password" name="pass"></label>
  <label><div>Password again</div> <input type="password" name="pass2"></label>
  <button type="submit" class="btn">Try</button>
</form>
<script>
  $(function() {
    $('#valid_form').scojs_valid({rules: {email: ['not_empty', 'email'], pass: ['not_empty', {'min_length': 4}], pass2: [{matches: 'pass'}]}});
  });
</script>

Usage

Via data attributes (data-api)

No data attributes support yet but this is something I plan on having eventually. Patches are welcome!

As a jquery plugin

$('#form').scojs_valid({rules: options, messages: options});

With access to the object

var valid = $.scojs_valid(formId, options);

This gives you access to the created javascript object. You will have to call the object's methods on your own to trigger validation. Normally, this is all wrapped in the jQuery plugin but if you want custom functionality or you don't want to depend on the jQuery form plugin, this is the way to do it. You'll probably want to call .validate() on the js object before submitting the form and handle the JSend response from the server later on.
formId can be either a string selector or a jQuery object.
options should be an object with rules and (optional) messages: {rules: {...}, messages: {...}}

Options

Name type default description
wrapper string label The wrapper of a form row. The default is set to label because the Mosto framework is using that. For Bootstrap you could use div.control-group. This option is used to add an .error class to the selected element whenever there's an error related to this field so that you can display the field or label/error message in a different color/style. If you set this to null, the error class won't be added at all.
rules object {} This is the set of rules that the whole form must pass for it to be submitted. The format of the object is field names as keys and arrays with rules as values:
{email: ['not_empty', 'email'], name: ['not_empty', {equals: 'john'}]}
See the list of rules below for what can be used here.
messages object {} The messages to display for each field in case of errors with that field. Could be useful for translating the messages into other languages. If you don't specify custom messages for your fields, the default ones will be used. See below for the default messages and message format.
onSuccess function The function to run when the backend sends a response with status == 'success'. The function receives the response, the validator object and the form as arguments. Returning false from this function will prevent the default onSuccess action.
$('#form').scojs_valid({
   rules: {...}
  ,onSuccess: function(response, validator, $form) {...}
});
onError function The function to run when the backend sends a response with status == 'error'. The function receives the response, the validator object and the form as arguments. Returning false from this function will prevent the default onError action.
$('#form').scojs_valid({
   rules: {...}
  ,onError: function(response, validator, $form) {...}
});
onFail function The function to run when the backend sends a response with status == 'fail'. The function receives the response, the validator object and the form as arguments. Returning false from this function will prevent the default onFail action.
$('#form').scojs_valid({
   rules: {...}
  ,onFail: function(response, validator, $form) {...}
});
onBeforeValidate function The function to run before trying any kind of validation on the form. This gives you the chance to alter form fields based on custom logic. It's very useful for WYSIWYG editors that need to be told to update the original textarea before trying to actually validate the form.
$('#form').scojs_valid({
   rules: {...}
  ,onBeforeValidate: function() {...}
});

Rules

Name type Example description
not_empty string 'not_empty' Use this rule if the field is required.
min_length object {min_length: 10} If the field is not empty, it has to have at least the specified number of characters. Note that an empty field will pass this rule! If you want the field to be required, use the not_empty rule.
max_length object {max_length: 20} If the field is not empty, it has to have at most the specified number of characters. Note that an empty field will pass this rule! If you want the field to be required, use the not_empty rule.
regex object {regex: /[a-z]/} The field must pass the specified regular expression.
email string 'email' The field must be a valid email.
url string 'url' The field must be a valid url.
exact_length object {exact_length: 10} If the field is not empty, it has to have exactly the specified number of characters. Note that an empty field will pass this rule! If you want the field to be required, use the not_empty rule.
equals object {equals: 'bar'} The field value must be exactly the specified string.
ip string 'ip' The field must be a valid IP address.
credit_card string 'credit_card' If the field is not empty, it must be a valid credit card. Note that an empty field will pass this rule! If you want the field to be required, use the not_empty rule.
alpha string 'alpha' If the field is not empty, it must contain only a to z characters.
alpha_numeric string 'alpha_numeric' Like alpha plus the 0 to 9 digits.
alpha_dash string 'alpha_dash' Like alpha_numeric plus underscore (_) and minus (-).
digit string 'digit' If the field is not empty, it must contain only digits (0 to 9).
numeric string 'numeric' If the field is not empty, it must be a valid number (negative and decimal numbers allowed). For example -123456.50
decimal string 'decimal' Alias for numeric.
matches object {matches: 'field1'} The field must match the specified field (have the same value as the other field).

Messages

The default messages used by the plugin, when no custom message is set. Note that any occurence of the string :value in the message is replaced by the rule constraint value.

Message for message
not_empty This field is required.
min_length Please enter at least :value characters.
max_length Please enter no more than :value characters.
regex
email Please enter a valid email address.
url Please enter a valid URL.
exact_length Please enter exactly :value characters.
equals
ip
credit_card Please enter a valid credit card number.
alpha
alpha_numeric
alpha_dash
digit Please enter only digits.
numeric Please enter a valid number.
decimal Please enter a decimal number.
matches Must match the previous value.

Communicate with the backend

Once the client side validation has passed, the form is submitted to the backend where you should have another round of validation. The backend can then tell the client what to do next: show some more errors, go to another page, show a Message and so on.
The instructions from backend to frontend are sent as json, in the JSend format.

Examples:
{"status":"success","data":{"next":"http://google.com"}}
{"status":"fail","data":{"errors":{"email":"This error comes from server side"}}}
{"status":"error","message":"The server made a boo boo"}

Name possible values description
status fail|error|success Use fail when there were validation errors on the server, error when there's a problem with the server and success when validation passed.
data This object is used for fail and success status codes to pass additional instructions to the frontend. Not used for error status codes.
  • with fail - data must be an object with a single errors key. The value of errors must be an object with field names as keys and error messages as values
    {"status":"fail","data":{"errors":{"email":"This email already exists", "name":"Enter your full name"}}}
  • with success - data must be an object with one of the following keys:
    • next - (optional) Can have a value of "." to refresh the current page, "x" to close the modal the form was display into or some url to redirect the browser to that url.
    • message - (optional) If set, a success flash message is displayed using Message.
message Used only with error status codes. An error flash message is displayed using Message.

Methods

.validate()

Performs the client side validation and show the errors on the form fields, if any. Returns true if all rules pass and false otherwise.

var valid = $.scojs_valid('#signup_form', {rules: {email: ['not_empty']}});
valid.validate();

What?

Panes is the core for tabs and carousels. Not meant to be used standalone, unless you want to provide functionality not covered by Tab and Carousel.

It provides the basic functionality to switch between a collection of elements - show one of them then hide that and show some other. Its aim is to be easily extensible - add any kind of transition effect you want, add callbacks, etc.
By default it comes with 3 transitions ( xfade, slide, flip ) but you can add as many as you want.

Why?

Tabs and carousels are basically the same thing (from a functional point of view): A collection of elements of which only one is visible at a time. You switch between the elements by clicking on tab headers or on navigation pills. Carousels are a bit more advanced than this but the core functionality is the same. It made sense to have a library to provide the common functionality for both. You can even think beyond just tabs and carousels - how about a pagination module that switches between pages (e.g. « 1 2 3...10 »)? Or a side menu that shows various pages with a nice transition between the pages? This pattern is quite used on the web.

Dependencies

If you want to use transitions you need to load bootstrap-transition.js before this.

Examples

<div class="pane-wrapper" id="panes-example">
  <div><img src="assets/img/carousel1.jpg"></div>
  <div><img src="assets/img/carousel2.jpg"></div>
</div>
<button class="btn" id="select-pane1">Show 1</button>
<button class="btn" id="select-pane2">Show 2</button>
<script>
  $(function() {
    var $panes = $.scojs_panes('#panes-example', {easing: 'flip'});
    $('#select-pane1').on('click', function() {
      $panes.select(0);
    });
    $('#select-pane2').on('click', function() {
      $panes.select(1);
    });
  });
</script>

Usage

With access to the object

var $panes = $.scojs_panes(selector, options);

Options

Name type default description
active integer 0 The index of the active pane (0 based).
easing string The css class to add to the wrapper. You could add the class yourself in html without specifying this option to the plugin but I might implement a javascript fallback for fade/slide so it's better that the plugin is aware of this. At the moment you can use xfade, slide and flip. You can, of course, define your own css-based transition effects, in which case you'd specify here the name of your css class.
For example, you could use easing: 'flip-vertical', copy all styles that start with .pane-wrapper.flip in scojs.css, replace .flip with .flip-vertical there and rotateY with rotateX.
onBeforeSelect function The callback to run just before selecting a new pane. If your callback returns false, the new pane will not be selected. Inside the function, this refers to the panes object so you can access all other object properties (like this.options, etc).

Methods

.select(index)

Select the index-th element (0-based). Returns true if the element was selected or false if not (selection might be blocked by the onBeforeSelect callback).

var $panes = $.scojs_panes('#foo', {active: 1});
$panes.select(0);

.prev()

Select the previous element. If the first element is active, prev() selects the last one. Returns true if the element was selected or false if not (selection might be blocked by the onBeforeSelect callback).

var $panes = $.scojs_panes('#foo', {active: 1});
$panes.prev();

.next()

Select the next element. If the last element is active, next() selects the first one. Returns true if the element was selected or false if not (selection might be blocked by the onBeforeSelect callback).

var $panes = $.scojs_panes('#foo');
$panes.next();

What?

This is really just a convenient utility function that makes links load remote content with AJAX inside some target element on the page. This behaviour is also known as "ajaxification of links". Could be used for a side menu - all menu links would load just the page content, without a full page reload.

Note that this function doesn't parse the output to display just a part of it in page and it doesn't make use of the browser history API. If you need such a full ajaxification plugin take a look at History.js.

Why?

I needed some links to load their contents with ajax but not all. There was no need for browser history API support or anything fancy.

Dependencies

Ajax does not depend on other libraries (other than jQuery, of course). However, we recommend you load spin.js. If spin.js is found, a spinning wheel is displayed during the loading of remote content.

Examples

Ajax demo
Remote content will be loaded here
<!-- Button to trigger ajax -->
<a data-trigger="ajax" href="lipsum2.html" data-target="#ajax_target" class="btn">Ajax demo</a>

Usage

Via data attributes (data-api)

<a data-trigger="ajax" href="lipsum.html" data-target="#ajax_target" class="btn">Ajax demo</a>

The data-api usage is "live" - meaning that you don't have to rebind new elements. Every new element having a data-trigger="ajax" attribute that is added to the dom after the initial load will work out of the box.

Options

Options are passed with attributes.

Name type default description
data-target string The container for the content. This option should point to an existing element on the page.
href string URL to load the content from.

What?

A simple countdown plugin, nothing fancy here. You tell it to countdown to a certain date/time and it starts counting while displaying the counter in the html element of your choice.

Why?

I needed this for an auction kind of app to show the remaining time. Not really related to bootstrap but could be useful to someone.

Dependencies

jQuery.

Examples

<div id="countdowner"></div>
<script>
$('#countdowner').scojs_countdown({until: 1364382956});
</script>

Usage

Via data attributes (data-api)

The plugin cannot be initiated with data-api but you can specify the options with data attributes on the target element:

<div id="countdowner" data-d="días" data-h="horas" data-m="minutos" data-s="segundos"></div>

As a jquery plugin

$('#target').scojs_countdown(options);

Options

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

Name type default description
until integer Unix timestamp (in seconds) to countdown to. This option is required.
d string d Text to show after the count of days. By default it shows 'd' as in 12d but if you change it to, say, 'days', it'll show 12days.
h string h Text to show after the count of hours. By default it shows 'h' as in 12h but if you change it to, say, 'hours', it'll show 12hours.
m string m Text to show after the count of minutes. By default it shows 'm' as in 12m but if you change it to, say, 'minutes', it'll show 12minutes.
s string s Text to show after the count of seconds. By default it shows 's' as in 12s but if you change it to, say, 'seconds', it'll show 12seconds.