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 ;)
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.
data-*
attributes and make it more extensible, otherwise this is a low priority for now.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.
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.
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.
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 | | 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.
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 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: "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.
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>
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:
<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.
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()). |
$('#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);
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). |
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.
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:
|
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);
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.
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. |
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: {...}}
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() {...} }); |
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. |
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.
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.
|
|
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="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);
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). |
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="lipsum2.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.
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. |
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.
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.
jQuery.
<div id="countdowner"></div> <script> $('#countdowner').scojs_countdown({until: 1364382956}); </script>
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>
$('#target').scojs_countdown(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. |