创造sco.js的起因是为了增强Bootstrap中现有的js组件,并且也为了满足我自己所做的项目的特定需求。 对于一般的使用而言,Bootstrap中的js插件非常棒,但是,一旦你有深层次的或特定需求的时候,他们就无法满足了。 大部分的Bootstrap js插件是(或者说,在我创造自己版本的插件前)无法扩展的,并且,我所面临的问题不仅仅是写一两行代码就能解决的。这并不是说Bootstrap和它的js组件很差劲!Bootstrap的确是一个非常好的快速开发框架,但是,你不能强求让他适应所有需求。在我的使用经历中,Bootstrap的确满足了大部分需求 :)
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。
data-*
属性,并且让他更易扩展,当然,现在还不着急。modal的主要用途是加载内容(通过ajax加载)并显示在一个覆盖层内,置于当前页面之上。当然,他还可以展示本地内容,这种使用方式不多。
由于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.
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.
$('#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 | | 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. |
$('#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:
Shows the modal.
var modal = $.scojs_modal({ keyboard: true }); modal.show();
Closes the modal.
var modal = $.scojs_modal({ keyboard: true }); modal.show(); modal.close();
Closes and destroys the modal, removes all modal HTML and events from the DOM.
var modal = $.scojs_modal({ keyboard: true }); modal.show(); modal.destroy();
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().
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.
<!-- Button to trigger confirm --> <a data-trigger="confirm" href="/delete/me" class="btn">Launch demo confirm</a>
<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.
$('#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 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. |
$('#trigger').scojs_confirm({ content: "Ain't that cute?", action: "https://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.
Accordions or show/hide togglers.
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"
).
<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:
<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>
<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.
$('#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()). |
$('#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:
Toggles the target element.
var collapse = $.scojs_collapse(); collapse.toggle();
Tab functionality for your pages.
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>
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:
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.
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.
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.
$('#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 the index-th element (0-based).
var $tab = $.scojs_tab('#foo'); $tab.select(1);
Y'know...tooltips. The kind of dialog baloon that usually appears on hover over stuff.
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.
<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.
$('.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:
|
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: |
$('#trigger').scojs_tooltip({ content: "Tooltip content" ,cssclass: 'pretty' ,delay: 1000 });
The following methods are available when you get access to the js object:
Shows the tooltip straight away.
var tooltip = $.scojs_tooltip('#trigger', { target: '#foo' ,content: 'tooltip content' }); tooltip.show();
Hides the tooltip straight away.
var tooltip = $.scojs_tooltip('#trigger', { target: '#foo' ,content: 'tooltip content' }); tooltip.show(); tooltip.hide();
See .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
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.
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.
<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>
$.scojs_message(message, type);
名称 | 类型 | 默认值 | 说明 |
---|---|---|---|
type | The type of the message. Can be one of:
|
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.
There are a couple of good form validators out there. I built this one because:
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>
No data attributes support yet but this is something I plan on having eventually. Patches are welcome!
$('#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) {...} }); |
名称 | 类型 | 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. |
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). |
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 | |
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. |
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":"https://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.
|
|
message | Used only with error status codes. An error flash message is displayed using Message. |
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();
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.
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="/static/example/sco/img/carousel1.jpg"></div> <div><img src="/static/example/sco/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 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);
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();
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();
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.
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.
<!-- Button to trigger ajax --> <a data-trigger="ajax" href="lipsum.html" data-target="#ajax_target" class="btn">Ajax demo</a>
<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. |
这是一个简单的倒计时(Countdown)插件,没什么太特别的。你给这个插件一个日期/时间,他就会在你指定的页面元素内展示出来,并开始计时。
我的项目中需要一个剩余时间提醒,因此就做了这个插件。和Bootstrap没有太大关系,但是可能对大家有些用处。
jQuery.
<div id="countdowner"></div> <script> $('#countdowner').scojs_countdown({until: 1364382956}); </script>
此插件无法使用data-api初始化,但是你可以通过data
属性在目标页面元素上指定参数:
<div id="countdowner" data-d="días" data-h="horas" data-m="minutos" data-s="segundos"></div>
$('#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. |