This is the guide for Onsen UI version 1. Onsen UI 2 contains a lot of additional features including Material Design components, React and Angular 2+ support, and many new components. If you are looking for documents for Onsen UI Version 2, please visit Version 2 Docs page. We also have Migration Guide from V1 to V2.
Note: For faster instructions to use Onsen UI in your project, please refer to Getting Started.
Even though Onsen UI uses AngularJS 1 to provide custom elements, it is not required to understand AngularJS. Onsen UI can be used with any JS frameworks including jQuery or Backbone.js, or with AngularJS 1 to have a tighter integration.
An Onsen UI app is actually an AngularJS 1 app. Here is the minimum boilerplate which should be very familiar to the AngularJS 1 users.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="lib/onsen/css/onsenui.css"/>
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css"/>
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="lib/onsen/js/onsenui.js"></script>
<script>
var module = ons.bootstrap('my-app', ['onsen']);
module.controller('AppController', function($scope) { });
module.controller('PageController', function($scope) {
ons.ready(function() {
// Init code here
});
});
</script>
</head>
<body ng-controller="AppController">
<ons-navigator var="navi">
<ons-page ng-controller="PageController">
<!-- Page content -->
</ons-page>
</ons-navigator>
</body>
</html>
Onsen UI provides a way to use without deeper understanding of AngularJS. For instance, the example below describes a sample app that is using Onsen UI and pure JavaScript:
<!doctype html>
<meta charset="utf-8">
<link rel="stylesheet" href="lib/onsen/css/onsenui.css">
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css">
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="lib/onsen/js/onsenui.js"></script>
<script>
ons.bootstrap();
ons.ready(function() {
// Add another Onsen UI element
var content = document.getElementById("my-content");
content.innerHTML="<ons-button>Another Button</ons-button>";
ons.compile(content);
});
</script>
<body>
<ons-navigator title="Navigator" var="myNavigator">
<ons-page>
<ons-button onclick="myNavigator.pushPage('page2.html')">Next Page</ons-button>
<div id="my-content"></div>
</ons-page>
</ons-navigator>
</body>
When you specify var
attribute when defining a component, the object is also defined in a window
object. For details, please see access to the component object from your code.
ons.compile
function converts your custom elements based HTML to a normal DOM structure. Most browsers does not (yet) support custom elements by default, you need to call the function every time to make the magic happen.
It is important to consider UI patterns before start implementation. Onsen UI supports 4 commonly used UI patterns. And remember, you can combine two or more patterns in your app. For example, a sliding menu app can also have page navigations.
This is the most common pattern if you want to have a parent-child relationship between pages. You can link to a child page from a button or a list item. In Onsen UI, you can follow navigation pattern by using <ons-navigator>
and <ons-toolbar>
.
Also referred to as a Menu pattern, it is useful if the app needs many pages in the same level. In Onsen UI, <ons-sliding-menu>
component supports this pattern. It also has swipe support when displaying or hiding sliding menu.
More commonly seen in iPhone and iPad apps, tab bar is displayed in the bottom of the page. Usually the tab bar items have an icon and a text. This pattern is frequently used when you want to provide several features in the app. Onsen UI way to display a tab bar is to use <ons-tabbar>
component.
This pattern is usually used for larger screen devices like tablets, or when rotating display in horizontal. It divides the screen into 2 columns, and displays two separate pages. <ons-split-view>
component allows you to use this pattern. It also has capability to hide sub-page on smaller devices or displayed vertically.
In Onsen UI, a page navigation is done by the <ons-navigator>
. <ons-navigator>
is a navigation controller that does not have displayed content. Therefore, you usually use a <ons-toolbar>
and add a toolbar on top of the page. Navigator provides screen transitions with smooth animation, and is used to create a parent-child relationship.
<ons-navigator>
is a page stack manager + transition animator. A new page added to the stack will have screen transition with animation. All pages in the stacks are the form of <ons-page>
elements; therefore only <ons-page>
components can be placed directly under a <ons-navigator>
element.
A page usually have a toolbar on top of the page. Therefore, <ons-toolbar>
component is commonly placed under <ons-page>
element to provide a back button support and the page title.
Click to Load this example.
To add a new page to the stack, use pushPage()
method in the navigator object. You can use var
attribute of <ons-navigator>
to refer the navigator object from JavaScript code.
<ons-navigator var="myNavigator"></ons-navigator>
<script>
var options = {
animation: 'slide', // What animation to use
onTransitionEnd: function() {} // Called when finishing transition animation
};
myNavigator.pushPage("page2.html", options);
</script>
As seen in the code, the configuration options can be set in the second parameter of pushPage()
method.
Similarly, use popPage()
method to remove the current foreground page from the stack.
<ons-navigator var="myNavigator"></ons-navigator>
<script>
myNavigator.popPage();
</script>
pushPage()
and popPage()
method can specify the following animation patterns: slide
, lift
, fade
and none
.
Slide animation (default)
The animation effect differs between iOS and Android to correspond to the native transition.
navigator.pushPage("page2.html", { animation: "slide" }):
Lift animation
navigator.pushPage("page2.html", { animation: "lift" }):
Fade-in & fade-out animation
navigator.pushPage("page2.html", { animation: "fade" }):
No animation
navigator.pushPage("page2.html", { animation: "none" }):
Click to Load this example.
Furthermore, you can customize the transition animation by specifying a new NavigatorTransitionAnimator
object to the animation
parameter.
pushPage('page2.html', {animation: new MyCustomAnimator})
For more details, please see NavigatorTransitionAnimator
source code located under framework/views
.
Navigator has several other APIs to manage page stacks. It is useful to have a fine-grain control.
Get a page
object of the current page. A page
object has following properties and functions.
destroy()
method
When it is called, the page is removed from the page stack.
options
object
An object that hold page configurations. See pushPage()
method description for details.
myNavigator.pushPage("page2.html", { param1: "value1", param2: "value2" });
var page = myNavigator.getCurrentPage();
console.log(page.options.param1); // Will return "value1"
Returns an array of page
objects from the navigator. See getCurrentPage()
method for the details how to use page
object.
// Remove the 2nd topmost page from the page stack
var pages = navigator.getPages();
pages[pages.length - 2].destroy();
// Now a popPage() will display pages[pages.length - 3]
Adds a page into any level in the stack by specifying the index
parameter. If specified as 0
, it will add the page to the bottom of the page stack. If specified a negative value, it will be counted from the top level. Therefore, specifying -1
will result in adding the page to the 2nd level from the top. The page
and options
parameters works the same as pushPage()
API.
Click to Load this example.
Replaces the current page with the specified one. The options
parameter corresponds to the navigator.pushPage
API.
Clears page stack and add the specified page to the new stack. The options
parameter corresponds to the navigator.pushPage
API.
A toolbar is defined as a <ons-toolbar>
component. Here is the typical example of a toolbar.
<ons-toolbar>
<div class="left">
<ons-back-button>Back</ons-back-button>
</div>
<div class="center">Title</div>
<div class="right">
<ons-toolbar-button>
<ons-icon icon="fa-bars">
</ons-toolbar-button>
</div>
</ons-toolbar>
Click to Load this example.
The toolbar is divided into 3 sections (left, center, and right), and they can be specified as class names (left
, center
, and right
). You can use <ons-icon>
to display an icon, <ons-toolbar-button>
or <ons-back-button>
to place an button, or insert any HTML content.
The appearance of the toolbar can be specified using modifier
attribute, with either android
or ios
value can be set. By default, Onsen UI will apply the appropriate style depending on the platform it run. If you specify fixed-style
, the toolbar style will be fixed regardless of the platform you apply to the toolbar.
Here are several examples when using <ons-toolbar>
.
<ons-toolbar>
<div class="left"><ons-toolbar-button>Button</ons-toolbar-button></div>
<div class="center">Button and Icon</div>
<div class="right"><ons-toolbar-button><ons-icon icon="fa-bars"></ons-icon></ons-toolbar-button></div>
</ons-toolbar>
<ons-toolbar>
<div class="left"><ons-back-button>Back</ons-back-button></div>
<div class="center">Search</div>
<div class="right"><input type="search" class="search-input" placeholder="Keyword"></input></div>
</ons-toolbar>
<ons-toolbar>
<div class="left"><ons-back-button>Back</ons-back-button></div>
<div class="center"><img src="custom_title.png"></div>
<div class="right"><ons-search-input></ons-search-input></div>
</ons-toolbar>
If you want to place a toolbar outsite the navigation header, you can create an <ons-toolbar>
or <ons-bottom-toolbar>
with inline
attribute.
<ons-toolbar inline>
<div class="center">Top Inline Toolbar</div>
<div class="left">Label</div>
</ons-toolbar>
<ons-bottom-toolbar inline>
<div class="center">Bottom Inline Toolbar</div>
<div class="left">Label</div>
</ons-bottom-toolbar>
Onsen UI supports Android back button. So, if the app is running on an Android device and using Cordova, pressing the back button will trigger a navigator’s popPage()
method.
If you additionally want to only show a back button from iOS devices, <ons-if-platform>
is the way.
<ons-toolbar>
<div class="left"><ons-back-button ons-if-platform="ios">Back</ons-back-button></div>
<div class="center">Page Title</div>
</ons-toolbar>
For more details about the device back button support, please take a look at the Handling Back Button section.
<ons-navigator>
has several events that can be hooked to do the specific jobs. For instance, you can cancel the page transition under some conditions.
There are several events defined in the navigator: prepush
, postpush
, prepop
, postpop
. They are called before or after the pushPage
or popPage
action.
The callback function will get an event
object. The event
object has several properties and methods for manipulation. For example, the following code cancels the pushPage
behavior.
ons.ready(function() {
myNavigator.on('prepush', function(event) {
var page = event.currentPage; // Get current page object
if (needsCancel) {
event.cancel(); // Cancel operation
}
});
});
prepush
events are fired before the pushPage, replacePage and resetToPage. prepop
events are fired before the popPage.
event
object has the following parameters.
currentPage
: Page object. See Managing Page Stacks for details.cancel()
: Call to cancel transition.navigator
: The <ons-navigator>
object.postpush
events are fired after the pushPage, replacePage and resetToPage. postpop
events are fired after the popPage.
event
object has the following parameters.
leavePage
: Page object of the current page.enterPage
: Page object of the new page.navigator
: <ons-navigator>
object.Sliding menu consists of two pages, which are referred to as main page and menu page. The menu page is also called a side page, which is usually hidden and shown from the edge. It can be displayed when tapping a button, or swiping from the edge of the screen.
You can also place a <ons-navigator>
in the main page to provide a navigation to even more pages.
<ons-sliding-menu>
component has an main-page
and a menu-page
. Those pages should be specified as attributes. It also has side
attribute to specify which side the behind page should be appeared.
The menu page and main page can be specified under <ons-sliding-menu>
tag by specifying menu
and main
class respectively.
<ons-sliding-menu>
<div class="menu">
<ons-page>
Menu page contents
</ons-page>
</div>
<div class="main">
<ons-page>
Main page contents
</ons-page>
</div>
</ons-sliding-menu>
Or, you can separate the pages in another template like the example below.
<ons-sliding-menu
main-page="page1.html"
menu-page="menu.html"
side="left"
var="menu">
</ons-sliding-menu>
<script type="text/ons-template" id="page1.html">
<ons-page>
<ons-toolbar>
<div class="left">
<ons-toolbar-button ng-click="menu.toggleMenu()"><ons-icon icon="fa-bars"></ons-icon></ons-toolbar-button>
</div>
<div class="center">Page 1</div>
</ons-toolbar>
<h1 style="text-align: center">Page1</h1>
</ons-page>
</script>
<script type="text/ons-template" id="page2.html">
<ons-page>
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="menu.toggleMenu()"><ons-icon icon="fa-bars"></ons-icon></ons-toolbar-button>
</div>
<div class="center">Page 2</div>
</ons-toolbar>
<h1 style="text-align: center">Page2</h1>
</ons-page>
</script>
<script type="text/ons-template" id="menu.html">
<ons-list>
<ons-list-item modifier="chevron" onclick="menu.setMainPage('page1.html', {closeMenu: true})">
page1.html
</ons-list-item>
<ons-list-item modifier="chevron" onclick="menu.setMainPage('page2.html', {closeMenu: true})">
page2.html
</ons-list-item>
</ons-list>
</script>
Click to Load this example.
<ons-sliding-menu>
provides the following methods to handle menu actions: openMenu()
, closeMenu()
, and toggleMenu()
.
When you want to omit the animation effect, you can specify animation
parameter to none
.
mySlidingMenu.openMenu({
animation: 'none'
});
Using close-on-tap
attribute of <ons-sliding-menu>
, the menu will be automatically closed by tapping the background.
<ons-sliding-menu close-on-tap>
</ons-sliding-menu>
To change the main and menu page manually, use setMainPage()
and setMenuPage()
methods. These methods can specify parameters in the second argument.
closeMenu
: Set true
to close the page after execution.callback
: Specify a callback function after the animation is finished.If you set swipeable
attribute in <ons-sliding-menu>
, it detects swipe actions and opens/closes the menu. Please be aware that you also need to specify swipe-target-width
and max-slide-distance
to enable swipe support.
If you set draggable
attribute, you can drag the menu page to do the open/close action.
You can specify the animation effect in type
attribute. The available values are reveal
(default), push
and overlay
.
There are 4 events where you can attach to the sliding menu object: preopen
, postopen
, preclose
, postclose
.
<script>
ons.ready(function() {
mySlidingMenu.on('preopen', function() {
console.log("Menu page is going to open");
});
});
</script>
<ons-sliding-menu var="mySlidingMenu">
A tab bar is composed of a <ons-tabbar>
component and <ons-tab>
components. Usually a tab bar has three to five items, and they are displayed with icons and labels. Each tab bar item is assigned to the different page.
To place a tab bar into your app, place a <ons-tabbar>
element. A <ons-tabbar>
element only accepts <ons-tab>
under the element.
Tab bar items can have an icon
attribute and a label
attribute. For the icon
attribute, please specify the same icon name used in <ons-icon>
element.
<ons-tabbar>
<ons-tab page="page1.html" label="Page 1" icon="square" active="true"></ons-tab>
<ons-tab page="page2.html" label="Page 2" icon="square"></ons-tab>
<ons-tab page="page3.html" label="Page 3" icon="square"></ons-tab>
<ons-tab page="page4.html" label="Page 4" icon="square"></ons-tab>
<ons-tab page="page5.html" label="Page 5" icon="square"></ons-tab>
</ons-tabbar>
Click to Load this example.
Tab bar is placed on the bottom of the screen by default. For typical Android applications, a tab bar is commonly placed on the top. To position the tab bar, the position
attribute is used. Please note that this attribute is only valid when initializing the component, and will be ignored when setting the value during runtime.
<ons-tabbar position="top">
<ons-tab page="page1.html" label="Page 1" icon="fa-square" active="true"></ons-tab>
<ons-tab page="page2.html" label="Page 2" icon="fa-square"></ons-tab>
<ons-tab page="page3.html" label="Page 3" icon="fa-square"></ons-tab>
</ons-tabbar>
If the page already contains a toolbar, the tab bar will be placed below the toolbar.
<ons-page>
<ons-toolbar>
<div class="center">Page Title</div>
</ons-toolbar>
<ons-tabbar position="top">
<ons-tab page="page1.html" icon="fa-square"></ons-tab>
<ons-tab page="page2.html" icon="fa-square"></ons-tab>
<ons-tab page="page3.html" icon="fa-square"></ons-tab>
</ons-tabbar>
</ons-page>
Click to Load this example.
You can customize the design of the tabs by using <ons-tab>
attributes.
To display a label and icon on the tab, label
and icon
attributes are used.
<ons-tab label="Label" icon="fa-square"></ons-tab>
You can contain HTML elements inside the <ons-tab>
element.
<ons-tabbar>
<ons-tab page="home.html">
<p>Home</p>
</ons-tab>
<ons-tab page="friends.html">
<p>Friends</p>
</ons-tab>
</ons-tabbar>
However, the child elements are ignored when label
or icon
attribute is specified.
A tab can change its content by its active state. To do so, define the underlying element with ons-tab-active
and ons-tab-inactive
attribute.
<ons-tab page="page.html">
<div ons-tab-active>
<!-- This content will be displayed when the tab is active -->
</div>
<div ons-tab-inactive>
<!-- This content will be displayed when the tab is inactive -->
</div>
</ons-tab>
By default, the specified page will be reloaded when the user taps on a tab. Using persistent
attribute in <ons-tab>
, the content will not be reloaded so that the content can be dynamically injected. To know that the tab is switched, you can use postchange
event on <ons-tabbar>
component.
Tab bar have some JavaScript APIs for fine-grain control over the page management. To call them, you should use a var
attribute as described in the Calling Component APIs from JavaScript section.
setActiveTab(index, options)
method can be used to display a specific tab page. The index
parameter is used to specify the tab page index, which starts from 0
. For the options
parameter, following properties can be specified.
keepPage
: If set to true
, it will not refresh content and display a new page (default: false
).animation
: The transition animation to the page. Currently none
and fade
is supported. (default: none
)getActiveTabIndex()
method returns the index of the active tab in the number. If there is no active tab, it returns -1
.
If you want to only load a page but not to change the active tab index, the loadPage()
method can be used.
tabbar.loadPage('newpage.html');
Please note that prechange
and postchange
event will not occur in this case.
<ons-tabbar>
has prechange
and postchange
events that are fired before or after the page switch. The event will get the following parameters.
index
: Next page index.tabItem
: Object containing the next page.When you want to cancel the event, you can use the cancel()
method on the prechange
event object.
tabbar.on('prechange', function(event) {
event.cancel();
});
List is a very popular pattern to display a set of data in a scrollable view. Onsen UI supports scrollable lists by using <ons-list>
and <ons-list-item>
tags.
To create a list, place a <ons-list>
tag and <ons-list-item>
tags.
Also, <ons-list-header>
can be used to represent grouped list items.
Here is the basic <ons-list>
example with scrollable content.
Click to Load this example.
This type of list is usually used with <ons-navigator>
to provide screen transitions.
Click to Load this example.
Lists are frequently used in the configuration pages. Here is a sample list with some form elements.
Click to Load this example.
With ons-lazy-repeat
only currently visible items are loaded into the DOM. Elements are removed automatically from the DOM when they are not visible anymore. ons-lazy-repeat
permits millions of elements to be rendered with close to no performance penalty.
Click to Load this example.
ons-lazy-repeat
relies on a delegate object that contains all the required information about the list.
The delegate
object should be attached to the scope of the same controller as the item list, so it is accessible from the view:
$scope.MyDelegate = {
configureItemScope: function(index, itemScope) {
console.log("Created item #" + index);
itemScope.item = {
name: 'Item #' + (index + 1)
};
},
calculateItemHeight: function(index) {
return 40;
},
countItems: function() {
return 10000000;
},
destroyItemScope: function(index, scope) {
console.log("Destroyed item #" + index);
}
};
configureItemScope
contains the information about the items, which can be dynamically created or loaded from a array of items.calculateItemHeight
returns the height of an item. It could be different for every item.countItems
returns the total number of items in the list.destroyItemScope
is an optional method that will be triggered everytime an item is unloaded. This can be used to destroy elements and remove event listeners in order to avoid memory leaks.var MyDelegate = {
createItemContent: function(index, oldContent) {
console.log("Created item #" + index);
var $element = $("<span>Item #"+(index+1)+"</span>");
return $element[0];
},
calculateItemHeight: function(index) {
return 40;
},
countItems: function() {
return 10000000;
},
destroyItemContent: function(index, element) {
console.log("Destroyed item " + index);
}
}
createItemContent
creates the content of every list item given its index. It should returns an HTML element.calculateItemHeight
returns the height of an item. It could be different for every item.countItems
returns the total number of items in the list.destroyItemContent
is an optional method that will be triggered everytime an item is unloaded. This can be used to destroy elements and remove event listeners in order to avoid memory leaks.ons-lazy-repeat
is a general attribute. In these examples it’s used with ons-list-item
but it’s not limited to this component. It works well with any tag where item heights are calculable, such as <div>
tags. When adding ons-lazy-repeat
to a tag the delegate object must also be specified: ons-lazy-repeat="MyDelegate"
.
For AngularJS, item properties can be accessed normally:
<ons-list>
<ons-list-item ons-lazy-repeat="MyDelegate">
{{ item.name }}
</ons-list-item>
</ons-list>
In jQuery or pure Javascript, the content is generated in the createItemContent
method, so there is no need to specify anything else in the view:
<ons-list>
<ons-list-item ons-lazy-repeat="MyDelegate">
</ons-list-item>
</ons-list>
Onsen UI provides three common alert dialogs with predefined style, or a custom designed dialog using <ons-alert-dialog>
component.
Click to Load this example.
To show an alert dialog, the quicker way is to use the following functions to display in the predefined style.
Alert dialog
ons.notification.alert()
function shows an alert with a button and a text message. The message can be written in HTML format.
ons.notification.alert({
message: 'Message',
// or messageHTML: '<div>Message in HTML</div>',
title: 'Dialog Title',
buttonLabel: 'OK',
animation: 'default', // or 'none'
// modifier: 'optional-modifier'
callback: function() {
// Alert button is closed!
}
});
Confirm dialog
ons.notification.confirm()
function is similar to the alert dialog, but can have multiple buttons.
ons.notification.confirm({
message: 'Do you want to close the dialog?',
// or messageHTML: '<div>Message in HTML</div>',
title: 'Dialog Title',
buttonLabels: ['Yes', 'No'],
animation: 'default', // or 'none'
primaryButtonIndex: 1,
cancelable: true,
callback: function(index) {
// -1: Cancel
// 0-: Button index from the left
}
});
Prompt dialog
ons.notification.prompt()
function shows a prompt dialog that contains with a text input box.
You can use <ons-alert-dialog>
component to display alert dialog with the custom content. Here is the sample alert dialog that has a customized style.
<ons-template id="alert-dialog.html">
<ons-alert-dialog var="alertDialog">
<div class="alert-dialog-title"><strong style="color: #ff3333">Critical Alert!</strong></div>
<div class="alert-dialog-content">
An error has occurred!
</div>
<div class="alert-dialog-footer">
<button class="alert-dialog-button" ng-click="alertDialog.hide(); alertDialog.show()">OK</button>
</div>
</ons-alert-dialog>
</ons-template>
<script>
ons.ready(function() {
ons.createAlertDialog('alert-dialog.html').then(function(alertDialog) {
alertDialog.show();
});
});
</script>
Click to Load this example.
As you have seen in the example, you should define a template which will be specified in ons.createAlertDialog()
function. This template must contain an <ons-alert-dialog>
tag.
When the ons.createAlertDialog()
function is called, it will return a Promise
that resolves to a AlertDialogView
object. For more details about using a AlertDialogView
object, please refer to Using DialogView
object in <ons-dialog>
description.
<ons-dialog>
is a general purpose component to show an dialog.
To show a dialog, create a template that contains an <ons-dialog>
tag, and use this template as the argument to ons.createDialog()
function. The function will return a Promise
object, which resolves to a DialogView
object when the dialog is created. You need to call the show()
method to actually show the dialog.
<ons-template id="dialogcontent.html">
<ons-dialog>
Any HTML code here
</ons-dialog>
</ons-template>
<script>
ons.ready(function() {
ons.createDialog('dialogcontent.html').then(function(dialog) {
dialog.show();
});
});
</script>
Click to Load this example.
The ons.createDialog()
method also accepts an options
object. One of the parameters, options.parentScope
, can be used to pass a scope object that the inner scope of the dialog will inherit from.
angular.module('myApp').controller('MyController', function($scope) {
ons.ready(function() {
ons.createDialog('dialog.html', {parentScope: $scope}).then(function(dialog) {
$scope.dialog = dialog;
});
});
// This variable will be available in the dialog scope as well.
$scope.myVariable = 'Hello!';
});
DialogView
objectDialogView
object is the main object that contains the dialog information. It has following methods to provide fine-grain control.
show(options)
, hide(options)
Shows or hides the dialog. You can specify animations
and callback
in the options
parameter to get more control.
isShown()
Returns true
if the dialog is shown.
destroy()
Hides the dialog and remove all related DOM elements.
setDisabled(disabled)
, isDisabled()
Makes the dialog disable and prohibits any interaction from the user.
setCancelable(cancelable)
, isCancelable()
Set the dialog cancelable, which means it will close automatically when pressing the back button.
getDeviceBackButtonHandler()
Get the back button handler for the component. For more details, please refer to Handling Back Button .
When using custom dialog, you can specify a callback function when dialog is opened or closed. The callback can be set as the callback
parameter when calling the show()
or hide()
method.
Also, <ons-dialog>
and <ons-alert-dialog>
provides following events.
preshow, prehide
Fired before showing or hiding the dialog. The callback function will get a dialog
property (or alertDialog
property) and a cancel
property. You can cancel the operation by setting cancel
to true.
myDialog.on("preshow", function(e) {
// e.dialog is a DialogView object
e.cancel();
});
postshow, posthide
Fired after showing or hiding the dialog. The callback function will get a dialog
(or alertDialog
) property, which is the DialogView
object.
Carousel provides a container to display multiple items in the element. It can be used as a full screen component, or inside another element.
<ons-carousel>
component is the container which can contain multiple <ons-carousel-item>
components. Each <ons-carousel-item>
represents items in the carousel.
A full-screen carousel can be shown by specifying fullscreen
attribute to <ons-carousel>
component.
<ons-carousel fullscreen swipeable overscrollable auto-scroll>
<ons-carousel-item>
Carousel Item 1
</ons-carousel-item>
<ons-carousel-item>
Carousel Item 2
</ons-carousel-item>
</ons-carousel>
Click to Load this example.
When you want to show a carousel within another component, you should specify its height and width by the CSS style. If the width is not specified, it will interpreted as 100%
.
<ons-carousel style="height: 200px; width: 50%" swipeable overscrollable auto-scroll>
<ons-carousel-item>
Carousel Item 1
</ons-carousel-item>
<ons-carousel-item>
Carousel Item 2
</ons-carousel-item>
</ons-carousel>
To display an indicator on the <ons-carousel>
, you can use <ons-carousel-cover>
component to dispay a content on the carousel. It will always shown on top of the carousel container.
<ons-carousel>
provides some more features by specifying attributes.
initial-index
attribute will specify which item to show at the initial view. Note the index number starts from 0
.
<ons-carousel style="height: 100px; width: 100px" initial-index="1" swipeable overscrollable auto-scroll>
<ons-carousel-item>
Carousel Item 1
</ons-carousel-item>
<ons-carousel-item>
Carousel Item 2
</ons-carousel-item>
</ons-carousel>
Click to Load this example.
The carousel scroll direction can be a left-right or top-bottom, which can be specified at direction
attribute. The possible values are horizontal
(default) or vertical
.
The carousel can have an overscroll animation, which bumps when there are no more items to scroll. To enable over-scroll animation, overscrollable
attribute should be specified.
When item-width
or item-height
attribute is specified, two or more items can be shown at the same time. item-width
is available only when the direction
attribute is set to horizontal
, and item-height
when set to vertical
accordingly. By default, it is set to 100%
, so only one item is shown in the container.
Click to Load this example.
Other than the options above, following attributes can be specified to customize the behavior.
auto-scroll
attribute
When it is set, the carousel item will automatically scrolled to fit into the container.
swipeable
attribute
Use this attribute to make your carousel swipeable or draggable.
auto-refresh
attribute
When this attribute is set the carousel will automatically be refreshed when the number of items change. Uses this when the carousel is used with ng-repeat
.
auto-scroll-ratio
attribute
A number between 0.0 and 1.0. It specifies how long distance the carousel must be dragged before it will auto-scroll to the next item on release.
Carousel can be controlled by JavaScript methods. You can use var
attribute of <ons-carousel>
to access to the carousel methods.
Following methods are provided to navigate items in the carousel.
next(options)
, prev(options)
Scroll to the next (or previous) item. Otherwise, it will scroll to the first (or last) item.
first(options)
, last(options)
Scroll to the first or last item.
setActiveCarouselItemIndex(index, options)
Show the item specified by the index
. The current active index can be obtained by calling getActiveCarouselItemIndex()
function.
All scroll methods can specify options
, which can contain animation
and callback
parameters.
myCarousel.next({
animation: "none",
callback: function() {
// Fired when the scroll is done
}
});
After you add an <ons-carousel-item>
element to the <ons-carousel>
, you must call refresh()
function to update the layout. In case you are using the auto-refresh
attribute this is not required.
<ons-carousel>
component has following events.
postchange
Fired when the active item is changed. The event will be supplied with an object that contains carousel
, activeIndex
, and lastActiveIndex
properties.
carousel
: Contains the carousel object.activeIndex
: The index of the current active item.lastActiveIndex
: The index of the previous active item.This event will not fired when the carousel is not initialized with auto-scroll
enabled, or the carousel item has different size than the container.
refresh
Fired when the carousel layout has changed, or refresh()
method is called.
overscroll
Fired when the item is overscrolled. The event will be supplied with an object that contains carousel
, activeIndex
, and lastActiveIndex
properties.
carousel
: Contains the carousel object.direction
: Overscroll direction. Can be one of left
, right
, up
or down
.activeIndex
: The index of the current active item.waitToReturn()
: A method that takes a promise and waits for the promise to be resolved (or rejected) before scrolling back.The following example uses waitToReturn(promise)
to keep overscroll until some job is done.
carousel.on('overscroll', function(event) {
var deferred = $q.defer(); // Use AngularJS 1 $q service
event.waitToReturn(deferred.promise);
window.setTimeout(function() {
deferred.resolve();
}, 3000);
// The carousel keeps its state for 3 seconds
})
Click to Load this example.
<ons-modal>
is useful when showing a dialog that needs to forbid any user interaction while the modal is shown. Typically a modal is used to display progress indicators or to request a user action explicitly.
<ons-modal>
component can have any HTML content inside the tag. The content will be shown with a black mask when toggle()
or show()
method is called.
Click to Load this example.
A popover provides an in-page container that is used to provide additional interactions or information for a specific component. Onsen UI provides <ons-popover>
component to show a popover.
Click to Load this example.
To show a popover, you need to define a popover as a HTML context using <ons-popover>
tag, and open the popover by ons.createPopover()
function function.
Here is the quick example of how a popover is defined and created.
<ons-template id="popover.html">
<ons-popover
style="height: 200px; width: 200px"
animation="fade">
<ons-page>
Popover content.
</ons-page>
</ons-popover>
</ons-template>
<script>
ons.ready(function() {
var targetElement = document.getElementById('myButton');
ons.createPopover('popover.html')
.then(function(popover) {
popover.show(targetElement);
});
});
</script>
The ons.createPopover()
method also accepts an options
object. One of the parameters, options.parentScope
, can be used to pass a scope object that the inner scope of the popover will inherit from.
angular.module('myApp').controller('MyController', function($scope) {
ons.ready(function() {
ons.createPopover('popover.html', {parentScope: $scope}).then(function(popover) {
$scope.popover = popover;
});
});
// This variable will be available in the popover scope as well.
$scope.myVariable = 'Hello!';
});
When the ons.createPopover()
function is called, it will return a Promise
object. The object resolves to the PopoverView
object which has following methods:
show(target[, options])
Displays the popover component at the specified target
. The target
can be a DomElement
, a query selector or a AngularJS 1 $event
.
You can specify following parameters in the options
.
animation
: You can specify either none
or fade
.hide()
Hides the popover. Please use with destroy()
to clean up the element to avoid memory leak.
<ons-popover>
has some properties to customize the behavior and the design.
The design can be switched using modifier
attribute, which can be selected from android
and ios
. You can apply your own CSS styles by specifying a unique name (i.e. mystyle
) to the modifier
attribute.
Click to Load this example.
direction
attribute can control the popover to open from what direction. It can be specified from up
, down
, left
, or right
, and furthermore be combined multiple directions separated by space characters. If the direction
attribute is not specified, it will automatically detects the appropriate direction.
<ons-popover>
has following events.
preshow
, prehide
Fired before showing or hiding the popover. The callback function provides an event object with following properties.
popover
: Contains the popover object.cancel
: Method to cancel the operation.If you want to cancel opening the popover, you could write a program like the one below.
myPopover.on('preshow', function(e) {
e.cancel();
});
postshow
, posthide
Fired after showing or hiding the popover. The callback function provides an event object, which has popover
property contains popover object.
The Pull Hook component adds “pull-to-refresh” behavior to an <ons-page>
or an <ons-scroller>
element. This feature is very convenient for manually fetching data from external sources (like a database, RSS feed or web API) into an application.
Click to Load this example.
<ons-pull-hook>
tag is used to create and display a new Pull Hook component. By default, Pull Hook will drag down all the content of the page when pulling it. The attribute fixed-content
will prevent the page content to be dragged along with the Pull Hook.
<ons-pull-hook ng-action="load($done)" var="loader">
<span ng-switch="loader.getCurrentState()">
<span ng-switch-when="initial"><ons-icon size="35px" icon="ion-arrow-down-a"></ons-icon> Pull down to refresh</span>
<span ng-switch-when="preaction"><ons-icon size="35px" icon="ion-arrow-up-a"></ons-icon> Release to refresh</span>
<span ng-switch-when="action"><ons-icon size="35px" spin="true" icon="ion-load-d"></ons-icon> Loading data...</span>
</span>
</ons-pull-hook>
The Pull Hook behavior is defined by the ng-action="load($done)"
attribute. This function will be executed when the page is pulled down and released.
There are three potential states, each one associated with a customizable graphical representation:
initial
: default state before any user interaction, the element remains in this status until it’s totally dragged down, going beyond its height limit.
preaction
: if the component is in this state it will execute its action if it’s released. It’s still possible to cancel the action by dragging the page up again.
action
: the pull hook will be in this state while its action is running. After the $done
function is called it will return to the initial
state.
<ons-pull-hook>
component has two attributes to define what action it should perform:
ng-action
: used to specify custom behavior when the page is pulled down. A $done
function is available to tell the component that the action is completed.
on-action
: same as ng-action
but can be used without AngularJS. A function called done
is available to call when the action is completed.
<ons-pull-hook>
component’s height attributes are very important, since they define when a state transition should occur. The two attributes are:
height
: specifies the height of the component. When pulled down further than this value it will switch to the “preaction” state. The default value is “64px”.
threshold-height
: specifies the threshold height. The component automatically switches to the “action” state when pulled further than this value. The default value is “96px”. A negative value or a value less than the height will disable this property.
Onsen UI provides various components for building forms.
<ons-button>
renders a button with different face types. You can change the appearance by using modifier
, should-spin
, animation
and disabled
attributes. modifier
attribute provides several predefined values to change the appearance.
To detect a tap event, you can use either onclick
or ng-click
attribute.
Click to Load this example.
<ons-switch>
is used to display a switch. A switch has an “on” and an “off” state. The state can be accessed by the isChecked()
method.
<script>
function changed() {
alert(mySwitch.isChecked() ? 'ON' : 'OFF');
}
</script>
<ons-switch var="mySwitch" onchange="changed()"></ons-switch>
Text input and textarea do not have their own custom elements. However, you can specify a predefined class to display in Onsen UI styles.
Text input
<input class="text-input" id="my-input">
Text area
<textarea class="textarea" id="my-textarea"></textarea>
Search input
<input type="search" class="search-input">
In all cases, you can use document.getElementById()
call or jQuery selector to obtain the component value.
alert(document.getElementById("my-input").value);
alert($("#my-input").val());
Click to Load this example.
Check box and radio button are provided as CSS components. Therefore, use the following HTML snippet to display each component.
<label class="checkbox">
<input type="checkbox">
<div class="checkbox__checkmark"></div>
<span class="ons-checkbox-inner"></span>
</label>
<label class="radio-button">
<input type="radio">
<div class="radio-button__checkmark"></div>
</label>
Onsen UI provides a grid system to place your elements in the screen. The grid system divides the screen into rows and columns, just like a spreadsheet. The width and height of each grid is adjustable, and you can also condense two or more grids in a row or column, into one grid.
The layout can be performed by combining <ons-row>
and <ons-col>
components. The width and height can be adjusted in a flexible way.
By default, all <ons-col>
inside a <ons-row>
will have the same width. You can specify any <ons-col>
elements to have a specific width and let others take the remaining width in a <ons-row>
.
<ons-row>
has align
attribute, and <ons-col>
has align
, size
, and offset
attributes. For the size
attribute, you can specify either in px
or %
.
You can see the following example to understand how <ons-row>
and <ons-col>
can provide flexible component placement.
Click to Load this example.
Onsen UI offers over 400 icons provided by Font Awesome and over 500 icons by Ionicons.
When displaying an icon, a <ons-icon>
component can be used. You can specify which icon to display by specifying to the icon
attribute.
If the value of icon
attribute starts with fa-
, appropriate Font Awesome icon is used. The list of available icons can be found on the Font Awesome Website. If icon
attribute has no prefix, Font Awesome collection will be used.
If the value of icon
attribute starts with ion-
, appropriate Ionicons icon is used. The list of available icons can be found on the Ionicons Website.
Here are some examples.
<ons-icon icon="fa-angle-left"></ons-icon>
<ons-icon icon="fa-angle-left" size="40px"></ons-icon>
<ons-icon icon="fa-angle-left" size="40px" rotate="90"></ons-icon>
<ons-icon icon="fa-angle-left" spin="true"></ons-icon>
Also, you can specify the icon size to display by using size attribute.
<ons-icon icon="fa-angle-left" size="40px">
Furthermore, you can rotate the icon.
<ons-icon icon="fa-angle-left" size="40px" rotate="90deg">
Icon can have an animation effect. This is useful for displaying spinners.
<ons-icon icon="fa-angle-left" spin="yes">
Click to Load this example.
Onsen UI supports the responsive design, where you can apply different CSS styles for different screen sizes. To do so, you will use the CSS Media Query and separate CSS definitions based on your preference.
Furthermore, Onsen UI supports a Split View user interface, where you can have two columns in a larger or horizontal screen, and one column for a smaller screen. It provides an easy way for the developer to both support smartphones and tablets without defining particular CSS styles.
CSS Media Query can be used to separate CSS definition based on screen resolution, screen size, and/or aspect ratio.
For example, the following media queries is an example to separate various screen sizes.
<style>
@media (min-width:320px) { /* smartphones, iPhone, portrait 480x320 phones */ }
@media (min-width:641px) { /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */ }
@media (min-width:961px) { /* tablet, landscape iPad, lo-res laptops ands desktops */ }
@media (min-width:1025px) { /* big landscape tablets, laptops, and desktops */ }
@media (min-width:1281px) { /* hi-res laptops and desktops */ }
</style>
Click to Load this example.
<ons-split-view>
component is used to provide an interface that separates the screen into two parts.
Also, it has an option to hide the secondary page when the screen size is smaller. This is very useful when you want to support smartphones and tablets together.
<ons-split-view>
component has the following attributes:
main-page
: Specify a page to display on the main section.secondary-page
: Specify a page to display on the side section.Click to Load this example.
<ons-split-view>
has collapse
attribute to specify when to collapse. The possible values are portrait
, landscape
, or width ##px
(i.e. width 300px
). For example, if set as portrait
and the device is in portrait orientation, the secondary page is hidden.
If using Onsen UI for a Web application, you typically want a loading screen that will appear before Onsen UI has loaded completely. When using ons-loading-placeholder
attribute, the element that has the attribute will be replaced to the specified page after the initialization.
<body>
<div ons-loading-placeholder="start.html">
Loading My Application...
</div>
<ons-template id="start.html">
<div>Welcome to my app!</div>
</ons-template>
</body>
If no page is provided to ons-loading-placeholder
attribute it will wait until ons.resolveLoadingPlaceholder(page)
is called.
Onsen UI also provides several general purpose APIs to help make developing your app easier.
ons.ready()
function is called when Onsen UI initialization is done. If the app is running under Cordova or PhoneGap, it will also wait for its initialization (ondeviceready
event).
This event is very useful to hide the splash screen to avoid a black screen during the page load. For example, the following code will hide the splash screen once Onsen UI is loaded completely.
ons.ready(function() {
// Hide Cordova splash screen when Onsen UI is loaded completely
// API reference: https://github.com/apache/cordova-plugin-splashscreen/blob/master/doc/index.md
navigator.splashscreen.hide()
});
ons.bootstrap()
function is a handy way to load Onsen UI with one line of code. What it really does is add the Onsen UI module to AngularJS, and make it callable from any scope in the app. It must be executed after onsenui.js
is loaded.
For instance, following code will load Onsen UI with ngAnimate
module. You can specify list of modules to add in the parameter. ons.bootstrap()
will return the AngularJS 1 module object which can be used to add services from now on.
<script>
var module = ons.bootstrap(['ngAnimate']); // Optionally loading ngAnimate module
module.controller("TopController", function($scope){ });
</script>
You can also specify the module name when calling ons.bootstrap()
.
<script>
ons.bootstrap('myApp', ['ngAnimate']); // Optionally loading ngAnimate module
angular.module('myApp').controller("TopController", function($scope){ });
</script>
If you want to load Onsen UI in more AngularJS 1 way, you can use a onsen
module.
<script>
// Assume 'ng-app' is defined as 'my-app'
var module = angular.module('my-app', ['onsen']);
module.controller('AppController', function($scope) { });
module.controller('PageController', function($scope) {
ons.ready(function() {
// Init code here
});
});
</script>
ons.compile()
function is used to compile the DOM elements that have Onsen UI components. Typical usage of the function is to manually add a snippet of HTML and render it.
Note that ons.compile()
must specify a HTMLElement
object to its argument. Also, the element must be appended to the DOM tree before calling ons.compile()
. Please see the example below.
ons.ready(function() {
var elm = $("<ons-button>New Button</ons-button>");
elm.appendTo($("body")); // Insert to the DOM first
ons.compile(elm[0]); // The argument must be a HTMLElement object
});
As of iOS 7, a status bar can be rendered above a WebView. Onsen UI automatically detects and adds the necessary margin on the top. However in some occations, it is necessary to disable this feature, when using Cordova StatusBar plugin for instance.
To manage the top margin for iOS devices, Onsen UI provides ons.enableAutoStatusBarFill()
function and ons.disableAutoStatusBarFill()
function. This feature is enabled by default, and needs to call the function before Onsen UI initialization complete (before ons.ready()
event).
/**
* Need to call during Onsen UI initialization
*/
// Disable auto margin for the iOS status bar
ons.disableAutoStatusBarFill();
// Enable auto margin for the iOS status bar
ons.enableAutoStatusBarFill();
ons.ready(function() { });
You can use either <ons-if-platform>
attribute or ons.platform
object to detect the platform.
<ons-if-platform>
attribute is useful when only displaying contents under some specific platforms. It accepts one or multiple space separated values.
<div ons-if-platform="ios">Content for only iPhone and iPad users</div>
In addition to it, ons.platform
object provides following methods to detect the platform by JavaScript.
ons.platform.isWebView()
: Returns true
if the app is running on the WebView.ons.platform.isIOS()
: Returns true
if the app is running under an iOS device.ons.platform.isAndroid()
: Returns true
if the app is running under an Android device.ons.platform.isIPhone()
: Returns true
if the app is running under an iPhone device.ons.platform.isIPad()
: Returns true
if the app is running under an iPad device.ons.platform.isBlackBerry()
: Returns true
if the app is running under a BlackBerry device.ons.platform.isOpera()
: Returns true
if the app is running under an Opera browser.ons.platform.isFirefox()
: Returns true
if the app is running under a Firefox browser.ons.platform.isSafari()
: Returns true
if the app is running under Apple Safari browser.ons.platform.isChrome()
: Returns true
if the app is running under Google Chrome browser.ons.platform.isIE()
: Returns true
if the app is running under Internet Explorer browser.ons.platform.isIOS7()
: Returns true
if the running iOS is version 7.0 or later.For testing purposes it also provides a way to select a platform:
ons.platform.select( platform )
: Sets the platform used to render the elements. Possible values are: “opera”, “firefox”, “safari”, “chrome”, “ie”, “android”, “blackberry”, “ios” or “wp”.Similar to ons-if-platform
attribute, <ons-if-orientation>
attribute can be used to switch content between portrait and landscape.
<div ons-if-orientation="portrait">Content only shown for portrait</div>
ons.enableAnimations()
and ons.disableAnimations()
are provided for testing purposes and performance on older devices. All the animations will be completely disabled.
It is a common case to detect a finger gesture and do a specific task. Onsen UI utilizes Hammer.js for gesture detection.
To detect a finger gesture, you must wrap the target DOM element using <ons-gesture-detector>
component. For instance, thefollowing code does a swipe-left detection for a specific element.
<ons-gesture-detector>
<div id="detect-area" style="width: 100px; height: 100px;">
Swipe Here
</div>
</ons-gesture-detector>
<script>
$(document).on('swipeleft', '#detect-area', function() {
console.log('Swipe left is detected.');
})
</script>
Or, use ng-gestureeventname
if you prefer an AngularJS 1 way.
<ons-gesture-detector ng-swipeleft="doSomething()">
<div id="detect-area" style="width: 100px; height: 100px;">
Swipe Here
</div>
</ons-gesture-detector>
Following gestures are supported.
drag
, dragleft
, dragright
, dragup
, dragdown
hold
, release
swipe
, swipeleft
, swiperight
, swipeup
, swipedown
tap
, doubletap
pinch
, pinchin
, pinchout
touch
, transform
, rotate
Sometimes, you want to do a certain action, or change appearance based on the software keyboard status. Onsen UI provides a way to handle keyboard events when your app is plugged in with Cordova Keybord Plugin or Ionic Keyboard Plugin.
To catch keyboard events in JavaScript, you can use ons.softwareKeyboard
API.
// Works with both Cordova and Ionic keyboard plugin
ons.softwareKeyboard.on('show', function() {
// Some code when the keyboard is shown
});
ons.softwareKeyboard.on('hide', function() {
// Some code when the keyboard is hidden
});
Android has a hardware back button. Onsen UI provides a way to customize the back button behavior by providing several hook points to its application.
To support device back button, you can use either on-device-backbutton
or ng-device-backbutton
attribute of the <ons-page>
component.
Here is the way to define a back button handler by ons-page
attribute.
<ons-page on-device-backbutton="doSomething()">
Some page content
</ons-page>
Or the AngularJS 1 way,
<ons-page ng-device-backbutton="doSomething()">
Some page content
</ons-page>
Also, you can use following ons-page
APIs to set the device back button handler.
<ons-page var="myPage">...</ons-page>
<script>
ons.ready(function() {
myPage.setDeviceBackButtonHandler(function() {
// Write your handler here
});
// Get the back button handler and disable it
var handler = myPage.getDeviceBackButtonHandler();
handler.disable();
});
</script>
Not only a ons-page
component, a ons-navigator
and a ons-sliding-menu
component also implement the default back button handlers. For instance, the ons-navigator
handler triggers a popPage()
when the back button is pressed. If you want to disable it, or change to the other behavior, you can use getDeviceBackButtonHandler()
API.
// To disable a navigator back button handler
navigator.getDeviceBackButtonHandler().disable();
// Or to change the behavior
navigator.getDeviceBackButtonHandler().setListener(function(event) {});
// Or to enable it again
navigator.getDeviceBackButtonHandler().enable();
As you see in the code, getDeviceBackButtonHandler()
API returns an object that has disable()
, enable()
, isEnabled()
and setListener(fn)
methods.
If you want to call a parent event handler, callParentHandler()
method will do the delegation. If the component’s handler is undefined or set to be disabled, the parent event handler will be called automatically.
myPage.getDeviceBackButtonHandler().setListener(function(event) {
// Call parent handler
event.callParentHandler();
});
The default back button behavior of an Onsen UI app is to close the application. This is the same behavior as other Android applications.
To override the behavior, you can use ons.setDefaultDeviceBackButtonListener
function. The following code confirms before closing the app (works for Cordova / PhoneGap only).
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Are you sure to close the app?",
function(index) {
if (index === 1) { // OK button
navigator.app.exitApp(); // Close the app
}
}
));
});
If you want to disable Onsen UI back button handlers completely, use ons.disableDeviceBackButtonHandler()
function. It is useful when you want to use Cordova / PhoneGap back button handler directly.
ons.ready(function() {
ons.disableDeviceBackButtonHandler();
// Use Cordova handler
window.document.addEventListener('backbutton', function() {
// Handle backbutton event
}, false);
});
Some components have JavaScript functions to provide features that needs to be called after launching the program. For instance, ons-navigator
has pushPage()
and popPage()
methods to display or hide a new page.
In order to use component APIs, it should be referred from the JavaScript code. For that purpose, you could use the var
attribute on the component, or use either ons.findComponent()
or ons.findParentComponentUntil()
function.
In order to call those APIs, you need to assign a variable to the component by using var
attribute. For instance, you can assign a variable called "myNavigator"
by the following code.
<ons-navigator var="myNavigator">
Now, myNavigator
has become a global accessible variable. It is defined in the window
object, and also in the AngularJS 1 global scope.
To use the defined variable, you can refer the variable like the code below.
<script>
myNavigator.pushPage('newpage.html');
</script>
Or, the AngularJS 1 way.
<script>
module.controller("PageController", function($scope) {
ons.ready(function() {
// Actually myNavigator object sits in the root scope
$scope.myNavigator.pushPage("newpage.html");
});
});
</script>
As described above, a component defined with var
attribute will create a property in window
object. You can change the targeting object if you don’t want the global scope to be polluted.
The following example changes the component base to a variable named onsenComponents
.
var onsenComponents;
ons.componentBase = onsenComponents;
Then, you can access to the components like the example below.
onsenComponents.myNavigator.doSomething();
ons.findComponent()
and ons.findParentComponentUntil()
functions are useful when specifying a component without assigning a variable.
ons.findComponent()
function queries the specified component in the given DOM. For instance, if you want to find a ons-switch
component which id
is my-switch
, you can query the component by the following code.
var mySwitch = ons.findComponent('ons-switch#my-switch', document.body);
ons.findParentComponentUntil()
function tries to find a component by digging into the parent DOM nodes. For instance, following code finds the parent navigator for a button element.
var currentNavigator = ons.findParentComponentUntil('ons-navigator', buttonDom);
Even though the Onsen UI components are custom elements based, you can query the component using the familiar DOM APIs.
<ons-navigator class="myNavigator"></ons-navigator>
<ons-button id="my-ons-button"</ons-button>
<ons-list>
<ons-list-item class="item1"></ons-list-item>
</ons-list>
<script>
// Using DOM API
document.getElementById("my-ons-button");
// Using jQuery
$("ons-navigator.myNavigator");
$("ons-list-item.item1");
$("ons-button").onclick(function() {
alert("Button is clicked!");
});
</script>
Some components supports events. By using those events, you can hook your code to a specific action in the component and customize the behavior.
For a list of events that a component supports, please see the component page. The <ons-navigator>
emits these events.
To add a handler to a event, use on()
, off()
and once()
method of the target component. Therefore, you need to define a variable of the component, as described in the previous section.
<script>
myNavigator.on("prepush", function() {
// Add a handler for prepush event
});
</script>
<script>
// on and off usage
var callback = function(event) {
}
myNavigator.on("prepush", callback);
myNavigator.once("prepush", callback);
myNavigator.off("prepush", callback);
</script>
The most frequently used action is a tap on the element, the event can be triggered by onclick
handler.
<ons-button onclick="alert('You tapped me!')">Click Me</ons-button>
Also, if you are familiar with AngularJS 1 events, you can also get the same event by ng-click
handler.
<ons-button ng-click="alert('You tapped me!')">Click Me</ons-button>
In both cases, thanks to the fastclick library, there is no 300ms delay when detecting the event. This means the app responds much quicker to the user interactions.
Component event handlers can also be added using HTML attributes. These attributes are all prefixed with ons-
followed by the event name. To catch the prepop
event emitted by the <ons-navigator>
the ons-prepop
attributes is used:
<ons-navigator ons-prepop="doSomething()">
...
</ons-navigator>
The value of the attribute should be an Angular expression, so in the case where you are not using AngularJS 1 these attributes can’t be used.
<ons-page>
provides a set of DOM events that will be fired in different moments of its life cycle. Use these events to alter the behavior on each page.
init
event is fired after <ons-page>
is attached to DOM. In order to provide backward compatibility, the old pageinit
event is still fired but will be deprecated in upcoming versions.
destroy
event is fired before <ons-page>
is destroyed and prior to DOM detachment.
show
event is fired every time <ons-page>
comes into view, i.e. when a new page is created and shown immediately or when an existing page shows up.
hide
event is fired every time <ons-page>
disappear from view, i.e. when a visible page is destroyed or is hidden but still exists in the page stack.
Page lifecycle events will be propagated to the page’s descendants so they are correspondingly shown, hidden or destroyed. For example, destroying <ons-navigator>
will throw hide
event only for the displayed page (navigator’s top page) and destroy
event for every page in navigator’s page stack.
Example:
<script>
document.addEventListener("init", function(event) {
if (event.target.id == "my-page") {
document.getElementById("my-content").innerHTML = "I am fine!";
}
}, false);
</script>
<ons-page id="my-page">
<div>Hello, how are you?</div>
<div id="my-content">This content will be replaced.</div>
</ons-page>
All components fire a ons-component-name:init
event when they are initialized. This event is useful when you want to access and execute the component method right after the initialization. The component initialized can be obtained as component
property in the callback function.
$(document).on('ons-navigator:init', '#my-navigator', function(event) {
var navigator = event.component;
navigator.pushPage('login.html');
});
All other component events are also fired as DOM events and the event name is prefixed with the component name. This DOM event will inherit all properties from the component event.
$(document).on('ons-dialog:preshow', '#my-dialog', function(event) {
if (dontShowDialog()) {
event.cancel();
}
});
Most of the components (i.e. <ons-navigator>
, <ons-sliding-menu>
and <ons-tabbar>
) provide events to control the behavior before and after the user interaction. For more details, please see the document for each component.
Some components require you to specify another HTML page. For instance, a <ons-sliding-menu>
needs to specify a start up page in following format.
<ons-sliding-menu
menu-page="menu.html"
main-page="content.html">
</ons-sliding-menu>
Instead of creating menu.html and content.html in separate files, you can also define the page content in the same page. This can be done by creating a <ons-template>
tag, or a script
tag with "text/ons-template"
type. It is very useful when you want to maintain smaller amount of files.
An <ons-template>
tag represents a template snippet. For example, following code defines a template called main.html
.
<ons-template id="main.html">
<!-- Here, we define the HTML content for main.html -->
<div>
Hello, this is the content of main.html
</div>
</ons-template>
Alternatively, a <script>
tag can also be used to define a template. In this case, you need to set the type
to text/ons-template
.
<script type="text/ons-template" id="main.html">
<!-- Here, we define the HTML content for main.html -->
<div>
Hello, this is the content of main.html
</div>
</script>
The templates defined above are also treated as an AngularJS 1 template cache. Therefore, $templateCache
service can be used for further integration. For more details, please see the AngularJS 1 $templateCache
description.
Modifier is a cross-component way to provide customizability for Onsen UI components. When a component is defined with a modifier
, it will have a separate class namespace so that you can apply custom styles to the component. Also, some components have several preset modifiers to change the appearance.
For example, each of the following buttons have different look.
<ons-button modifier="quiet">Quiet</ons-button>
<ons-button modifier="light">Light</ons-button>
<ons-button modifier="large">Large</ons-button>
<ons-button modifier="cta">CTA</ons-button>
You can also dynamically switch the modifier in the component by JavaScript. All components that has modifier
attribute have following methods.
hasModifier(name)
: Returns true if the component have the specified modifier. You can add multiple test names separated in the space characters, which returns true if all modifiers are found.removeModifier(name)
: Remove the modifier from the component.addModifier(name)
: Add the modifier to the component.setModifier(name)
: Removes all modifiers and set new modifier(s) specified in the name
parameter.toggleModifier(name)
: Adds or removes the modifier.You can customize Onsen UI components based on what you want to achieve. You can either customize its look & feel, or go more deeper into the component and modify its underlying JavaScript or HTML code.
Onsen UI styles are defined in a CSS file called onsenui.css
and onsen-css-components.css
. These files have all the definitions. All components are fully customizable by editing the file.
Or, you can also use Onsen CSS Components to customize pre-defined colors. After the customization, you can download and replace to the existing onsenui-css-components.css
to reflect the changes.
There are some situations where you want to apply a different style to a specific component. In such case, you can use modifier attribute to override its style definition.
For example, if you want to apply a thick border only to a specific button, you can define like the one below.
<ons-button modifier="thick">Thick Button</ons-button>
Then, write the appropriate style code under the style tag or in the css file.
<style>
.button--thick {
border: 10px;
}
</style>
If you need to customize the underlying HTML code, you need to understand about AngularJS 1 directive. AngularJS 1 directive is a way to combine HTML code and JavaScript into a HTML tag.
HTML code for each components are located under the framework’s templates
directory. For instance, the HTML code for <ons-button>
is found in framework/templates/button.tpl
.
<button class="{{item.animation}} button--{{onsType}} effeckt-button button no-select {{modifierTemplater('button--*')}}">
<span class="label ons-button-inner" ng-transclude></span>
<span class="spinner button__spinner {{modifierTemplater('button--*__spinner')}}"></span>
</button>
After modifying the template files, you need to build Onsen UI because all the template files are cached and stored in framework/directives/templates.js
file. See Building Onsen UI section for more details.
The JavaScript code for each component is located in the directives
directory.
If you need to build Onsen UI manually, there is a gulp
task for that purpose. Please follow the instruction from the project Website.
If you have any questions, use our Community Forum or talk to us on Discord chat. The Onsen UI team and your peers in the community will work together to help solve your issues.
For bug reports and feature requests use our GitHub Issues page.