View on GitHub

Sco.js

Bootstrap javascript组件的增强版

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

Why?

创造sco.js的起因是为了增强Bootstrap中现有的js组件,并且也为了满足我自己所做的项目的特定需求。 对于一般的使用而言,Bootstrap中的js插件非常棒,但是,一旦你有深层次的或特定需求的时候,他们就无法满足了。 大部分的Bootstrap js插件是(或者说,在我创造自己版本的插件前)无法扩展的,并且,我所面临的问题不仅仅是写一两行代码就能解决的。这并不是说Bootstrap和它的js组件很差劲!Bootstrap的确是一个非常好的快速开发框架,但是,你不能强求让他适应所有需求。在我的使用经历中,Bootstrap的确满足了大部分需求 :)

注意: Bootstrap中默认使用css过渡(transition)效果,这非常好!我所创建的插件中仅有几个使用到了过渡(transition)效果,而且我也正在容许的情况下尽量使用。

你的收获

sco.js中的插件可以和Bootstrap一起使用,也可以单独使用。而且,sco.js中还包含了Bootstrap中没有的插件。所有插件都进行了单元测试,并且有生产环境的使用案例。每个插件都可以通过data-attributes data-trigger="pluginName" 或者 js代码 var $modal = $.scojs_modal({...})的方式使用。 E每个插件都有“创建原因”(看下面具体说明) -- 它为了实现什么目的、它和Bootstrap中的插件有何不同、我为什么首先创建它。

大部分的css都来源于Bootstrap。我也尽量遵循Bootstrap文档,遵循Bootstrap中的格式和约定,因此,你在使用的时候不会感觉和Bootstrap有很大不同。

如果data属性可以出发某个插件,代码将是:data-trigger="plugin name",以确保不和Bootstrap中的data-toggle="plugin name"产生冲突。 这样你就可以同时或交叉使用Bootstrap和sco.js。

接下来?

  • 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.
  • form 校验对ARIA的支持。
  • 如果足够有用,我将更新form校验,让他支持data-*属性,并且让他更易扩展,当然,现在还不着急。
  • 你有其他建议吗?

What?

modal的主要用途是加载内容(通过ajax加载)并显示在一个覆盖层内,置于当前页面之上。当然,他还可以展示本地内容,这种使用方式不多。

Why?

由于Bootstrap中的modal不支持加载远程内容,因此就建造了这个插件。还有,我不希望在使用modal的时候将modal的内容/HTML放入当前页面,这样会让整个页面乱糟糟的。只须一个链接就能让Sco.js中的modal组件运作起来。

例如,我们有一个旅馆的网站,每个房间都有一个订房表单,与其为每个页面放入相同的表单代码,还不如将这个表单单独做成一个页面,例如"my-booking-form.html",然后每次调用modal时就用ajax加载 href="my-booking-form.html" ,这样就能让页面的主要内容干净且对seo友好。

依赖

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.

案例

<!-- 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.

用法

通过data属性(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.

作为jquery插件使用

$('#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.

访问插件的对象实例

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.

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如data-keyboard="1".

名称 类型 默认值 说明
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.

依赖

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

案例

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>

用法

通过data属性(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.

作为jquery插件使用

$('#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.

访问插件的对象实例

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.

参数

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如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:

名称 类型 默认值 说明
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.

方法

.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.

依赖

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

案例

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>

更多案例:

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>

用法

通过data属性(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.

作为jquery插件使用

$('#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>

访问插件的对象实例

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.

参数

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如data-parent=".foo".

名称 类型 默认值 说明
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()).

方法

.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.

依赖

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.

案例

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.

用法

通过data属性(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.

作为jquery插件使用

$('#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.

访问插件的对象实例

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

参数

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如data-content="#foo".

名称 类型 默认值 说明
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).

方法

.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.

依赖

jQuery.

案例

<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.

用法

通过data属性(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.

作为jquery插件使用

$('.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.

访问插件的对象实例

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.

参数

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如data-content="my content".

名称 类型 默认值 说明
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:

方法

.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.

依赖

jQuery.

案例

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>

用法

作为jquery插件使用

$.scojs_message(message, type);

参数

名称 类型 默认值 说明
type The type of the message. Can be one of:
  • $.scojs_message.TYPE_OK
  • $.scojs_message.TYPE_ERROR

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.

依赖

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.

案例

<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>

用法

通过data属性(data-api)

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

作为jquery插件使用

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

访问插件的对象实例

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: {...}}

参数

名称 类型 默认值 说明
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) {...}
});

Rules

名称 类型 Example 说明
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.

案例:
{"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"}

名称 possible values 说明
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.

方法

.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.

依赖

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

案例

<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>

用法

访问插件的对象实例

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

参数

名称 类型 默认值 说明
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).

方法

.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.

依赖

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.

案例

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

用法

通过data属性(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 are passed with attributes.

名称 类型 默认值 说明
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?

这是一个简单的倒计时(Countdown)插件,没什么太特别的。你给这个插件一个日期/时间,他就会在你指定的页面元素内展示出来,并开始计时。

Why?

我的项目中需要一个剩余时间提醒,因此就做了这个插件。和Bootstrap没有太大关系,但是可能对大家有些用处。

依赖

jQuery.

案例

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

用法

通过data属性(data-api)

此插件无法使用data-api初始化,但是你可以通过data属性在目标页面元素上指定参数:

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

作为jquery插件使用

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

参数

可以通过data属性或者JavaScript代码传递参数。对于data属性,将参数名添加到data-之后,例如data-d="days"

名称 类型 默认值 说明
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.