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.

Loading Onsen UI in Your Project

Note: For faster instructions to use Onsen UI in your project, please refer to Getting Started.

Even though Onsen UI uses AngularJS 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 to have a tighter integration.

Onsen UI with AngularJS

An Onsen UI app is actually an AngularJS app. Here is the minimum boilerplate which should be very familiar to the AngularJS 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 with plain JavaScript

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.

Managing Multiple Pages

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

Sliding menu pattern

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.

Tab bar pattern

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.

Split view pattern

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.

Navigator overview

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

Run this example.

Click to Load this example.

Display a new page

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.

Returning from a page

Similarly, use popPage() method to remove the current foreground page from the stack.

<ons-navigator var="myNavigator"></ons-navigator>
<script>
myNavigator.popPage();
</script>

Transition animation

pushPage() and popPage() method can specify the following animation patterns: slide, lift, fade and none.

  1. Slide animation (default)

    The animation effect differs between iOS and Android to correspond to the native transition.

    navigator.pushPage("page2.html", { animation: "slide" }):
    
  2. Lift animation

    navigator.pushPage("page2.html", { animation: "lift" }):
    
  3. Fade-in & fade-out animation

    navigator.pushPage("page2.html", { animation: "fade" }):
    
  4. No animation

    navigator.pushPage("page2.html", { animation: "none" }):
    
Run this example.

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.

Managing page stacks

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.

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.

Run this example.

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.

Adding a toolbar

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>
Run this example.

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

  1. Example with a button and an icon
<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>
  1. Example with a search box
<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>
  1. Example with custom image
<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>
Inline 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>

Android back button

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 and prepop events

prepush events are fired before the pushPage, replacePage and resetToPage. prepop events are fired before the popPage. event object has the following parameters.

Postpush and postpop events

postpush events are fired after the pushPage, replacePage and resetToPage. postpop events are fired after the popPage. event object has the following parameters.

Using Sliding Menu

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.

Sliding Menu overview

<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>
Run this example.

Click to Load this example.

Opening / closing menu

<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'
});
Closing menu by tapping the background

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>

Setting menu and main page with JavaScript

To change the main and menu page manually, use setMainPage() and setMenuPage() methods. These methods can specify parameters in the second argument.

Swipe and drag support

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.

Animation type

You can specify the animation effect in type attribute. The available values are reveal(default), push and overlay.

Sliding menu events

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

Using Tab Bar

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.

Tab Bar overview

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>
Run this example.

Click to Load this example.

Placing tab bar on the top

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>
Run this example.

Click to Load this example.

Customizing tab bar

You can customize the design of the tabs by using <ons-tab> attributes.

Tab with label and icon

To display a label and icon on the tab, label and icon attributes are used.

<ons-tab label="Label" icon="fa-square"></ons-tab>
Tab with custom content

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.

Tab with state

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>
Do not reload when switching tabs

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.

Managing tab items

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.

Setting active tab

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.

Get current active tab

getActiveTabIndex() method returns the index of the active tab in the number. If there is no active tab, it returns -1.

Load page without changing the active tab

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.

Tab bar events

<ons-tabbar> has prechange and postchange events that are fired before or after the page switch. The event will get the following parameters.

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();
});

Using List

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.

List overview

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.

Basic list

Here is the basic <ons-list> example with scrollable content.

Run this example.

Click to Load this example.

List with right arrow icon

This type of list is usually used with <ons-navigator> to provide screen transitions.

Run this example.

Click to Load this example.

List with forms

Lists are frequently used in the configuration pages. Here is a sample list with some form elements.

Run this example.

Click to Load this example.

Using Lazy Repeat (or Infinite Scrolling)

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.

Run this example.

Click to Load this example.

Preparing a “delegate” object for Lazy Repeat

ons-lazy-repeat relies on a delegate object that contains all the required information about the list.

Delegate object in AngularJS

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);
  }
};
Delegate object using jQuery
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);
  }
}

Adding Lazy Repeat to tags

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>

Using Alert Dialog

Onsen UI provides three common alert dialogs with predefined style, or a custom designed dialog using <ons-alert-dialog> component.

Run this example.

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.

Showing a custom alert dialog

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>
Run this example.

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.

Using Dialog

<ons-dialog> is a general purpose component to show an dialog.

Showing 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>
Run this example.

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!';
});

Using the DialogView object

DialogView object is the main object that contains the dialog information. It has following methods to provide fine-grain control.

Handling dialog events

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.

Using Carousel

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.

Showing full screen 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>
Run this example.

Click to Load this example.

Showing carousel in a page

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>

Showing content (indicator) on 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.

Customizing carousel

<ons-carousel> provides some more features by specifying attributes.

Specifying initial carousel item

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>
Run this example.

Click to Load this example.

Specifying carousel scroll direction

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.

Specifying over-scroll animation

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.

Showing multiple items

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.

Run this example.

Click to Load this example.

Other carousel options

Other than the options above, following attributes can be specified to customize the behavior.

Controlling carousel by JavaScript

Carousel can be controlled by JavaScript methods. You can use var attribute of <ons-carousel> to access to the carousel methods.

Scrolling items

Following methods are provided to navigate items in the carousel.

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
  }
});
Adding carousel items by JavaScript

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.

Using carousel events

<ons-carousel> component has following events.

Using Modal

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

Run this example.

Click to Load this example.

Using Popover

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.

Run this example.

Click to Load this example.

Showing popover

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:

Customizing popover

<ons-popover> has some properties to customize the behavior and the design.

Changing appearance

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.

Run this example.

Click to Load this example.

Opening directions

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.

Using popover events

<ons-popover> has following events.

Using Pull Hook

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.

Run this example.

Click to Load this example.

Displaying Pull Hook

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

Pull Hook actions

<ons-pull-hook> component has two attributes to define what action it should perform:

Pull Hook height parameters

<ons-pull-hook> component’s height attributes are very important, since they define when a state transition should occur. The two attributes are:

Using Form Components

Onsen UI provides various components for building forms.

Button

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

Run this example.

Click to Load this example.

Switch

<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

Text input and textarea do not have their own custom elements. However, you can specify a predefined class to display in Onsen UI styles.

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());
Run this example.

Click to Load this example.

Check box and radio button

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>

Layouting

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.

Row and Col overview

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

Layout example

You can see the following example to understand how <ons-row> and <ons-col> can provide flexible component placement.

Run this example.

Click to Load this example.

Using Icons

Onsen UI offers over 400 icons provided by Font Awesome and over 500 icons by Ionicons.

Icon overview

When displaying an icon, a <ons-icon> component can be used. You can specify which icon to display by specifying to the icon attribute.

Using Font Awesome

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.

Using Ionicons

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">
Run this example.

Click to Load this example.

Multi-screen support

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.

Using CSS Media Query

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>
Run this example.

Click to Load this example.

Using Split View component

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

Run this example.

Click to Load this example.

Specify when to collapse

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

Showing Loading Screen

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.

Utility APIs

Onsen UI also provides several general purpose APIs to help make developing your app easier.

ready function

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()
});

bootstrap function

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

compile function

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
});

disableAutoStatusBarFill function

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() { });

Platform detection

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.

For testing purposes it also provides a way to select a platform:

Landscape / portrait detection

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>

Enable / disable animations

ons.enableAnimations() and ons.disableAnimations() are provided for testing purposes and performance on older devices. All the animations will be completely disabled.

Detecting Finger Gestures

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

<ons-gesture-detector ng-swipeleft="doSomething()">
  <div id="detect-area" style="width: 100px; height: 100px;">
    Swipe Here
  </div>
</ons-gesture-detector>

Supported gestures

Following gestures are supported.

Soft Keyboard Support

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
});

Back Button Support

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

Overriding default component handler

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();
});

Overriding the default app handler

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
      }
    }
  ));
});

Disabling back button handler

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);
});

Calling Component APIs from JavaScript

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.

Using ‘var’ attribute to specify a component

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

<script>
  module.controller("PageController", function($scope) {
    ons.ready(function() {
      // Actually myNavigator object sits in the root scope
      $scope.myNavigator.pushPage("newpage.html");
    });
  });
</script>
Changing component base object

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();

Querying a component from the DOM tree

ons.findComponent() and ons.findParentComponentUntil() functions are useful when specifying a component without assigning a variable.

ons.findComponent(selector, dom)

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(componentName, element)

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

Dealing with DOM APIs

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>

Event Handling

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>

Tap & click event

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

Event handler attributes

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 these attributes can’t be used.

Page life cycle events

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

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>

Component DOM events

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();
  }
});

Component events

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.

Defining Multiple Pages in Single HTML

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.

Use <ons-template> tag to define a template

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>

Use <script> tag to define a 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>

Using $templateCache from AngularJS

The templates defined above are also treated as an AngularJS template cache. Therefore, $templateCache service can be used for further integration. For more details, please see the AngularJS $templateCache description.

Using Modifier

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.

Customizing Onsen UI

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.

Customizing its look and feel

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.

Overriding CSS styles

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>

Customizing underlying HTML

If you need to customize the underlying HTML code, you need to understand about AngularJS directive. AngularJS 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.

Customizing JavaScript code

The JavaScript code for each component is located in the directives directory.

Building Onsen UI

If you need to build Onsen UI manually, there is a gulp task for that purpose. Please follow the instruction from the project Website.

Need Help?

If you have any questions, use our Community Forum or talk to us via Gitter 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.