Quickstart: adding WinJS controls and styles (HTML)

Applies to Windows and Windows Phone

The Windows Library for JavaScript provides a set of new controls designed for Windows Store apps using JavaScript, such as the WinJS.UI.DatePicker, WinJS.UI.FlipView, WinjS.UI.ListView, and WinJS.UI.Rating controls. It also includes two style sheets (one with a dark color scheme and one with a light) that give your app the look and feel of Windows 8.

See this feature in action as part of our App features, start to finish series: Windows Store app UI, start to finish.

Caution  The procedures in this article use the DatePicker and Rating controls, which are not supported on Windows Phone 8.1. For a complete list of supported WinJS controls on Windows Phone 8.1, see WinJS API changes on Windows Phone 8.1.

Prerequisites

What is the Windows Library for JavaScript?

The WinJS is a library of CSS and JavaScript files. It contains JavaScript objects, organized into namespaces, designed to make developing Windows Store app using JavaScript easier. WinJS includes objects that help you handle activation, access storage, and define your own classes and namespaces. It also includes a set of controls:

ControlDescription

AppBar

Displays commands.

BackButton

A button that provides backward navigation to the user.

DatePicker

Enables the user to select a date.

FlipView

Displays a collection of items, one item at a time.

Flyout

Displays a message that requires user interaction. (Unlike a dialog box, a Flyout doesn't create a separate window.)

ListView

Displays a collection of items in a grid or list layout.

HtmlControl

Displays an HTML page.

ItemContainer

Creates an item that can be pressed, swiped, and dragged.

Menu

A menu flyout for displaying commands.

NavBar

A type of AppBar that displays navigation commands.

PageControl

A set of HTML, JavaScript, and CSS that describes a page. You can navigate to a PageControl or use it like a custom control.

Rating

Lets the user rate an item.

Repeater

Generates HTML from a set of data and a template.

SearchBox

Enables the user to perform search queries and select suggestions.

SemanticZoom

Lets the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view.

SettingsFlyout

Provides users with fast, in-context access to app settings.

TimePicker

Enables the user to select a time.

ToggleSwitch

Turns an item on or off.

Tooltip

Displays a tooltip that can support rich content (such as images and formatted text) to show more info about an object.

ViewBox

Scales a single child element to fill the available space without resizing it. The control reacts to changes in the size of the container, and to changes in size of the child element. For example, this control responds if a media query results in a change in aspect ratio.

x-ms-webview

Displays HTML content. Use this control to display web pages in your app.

 

(For the complete list of controls, see the Controls list.)

WinJS also provides styling features in the form of CSS styles and classes that you can use or override. (Control styling is described in Quickstart: styling controls.)

Adding the Windows Library for JavaScript to your page

To use WinJS, your app must contain the WinJS files and each page that uses WinJS features must have the proper CSS and script references.


    <!-- WinJS style sheets (include one) -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet">
    <link href="//Microsoft.WinJS.2.0/css/ui-light.css" rel="stylesheet">

    <!-- WinJS code -->
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

When you use Microsoft Visual Studio to create a Windows Store app using JavaScript, it automatically includes the files you need. This example shows the default.html page for a project that uses the Blank App template.


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Adding WinJS controls and styles</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

    <!-- AddingWinJSControlsAndStyles references -->
    <link href="/css/default.css" rel="stylesheet">
    <script src="/js/default.js"></script>
</head>
<body>
    <p>Content goes here</p>
</body>
</html>

Adding a WinJS control in markup

Unlike HTML controls, WinJS controls don't have dedicated markup elements: you can't create a Rating control by adding a <rating /> element, for example. To add a WinJS control, you create a div element and use the data-win-control attribute to specify the type of control you want. To add a Rating control, you set the attribute to "WinJS.UI.Rating".

You must also call the WinJS.UI.processAll function in your JavaScript code. WinJS.UI.processAll parses your markup and instantiates any WinJS controls it finds.

The next set of examples show you how to add a WinJS control to a project created with the Blank Application template. It's easier to follow along if you create a new Blank Application project.

Hh465493.wedge(en-us,WIN.10).gifTo create a new project using the Blank Application template

  1. Launch Visual Studio.

  2. From the Start Page tab, click New Project. The New Project dialog box opens.

  3. In the Installed pane, expand JavaScript and click the Windows Store app template type. The available project templates for JavaScript are displayed in the center pane of the dialog box.

  4. In the center pane, pick the Blank Application project template.

  5. In the Name text box, enter a name for your project.

  6. Click OK to create the project. This will take a moment.

Hh465493.wedge(en-us,WIN.10).gifTo add a WinJS control

  1. Create a div element where you want to place the control. Set its data-win-control attribute to the fully qualified name of the control you want to create. This example creates a Rating control on the app's start page (the default.html file).

    
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Adding WinJS controls and styles</title>
    
        <!-- WinJS references -->
        <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet">
        <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
        <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>
    
        <!-- AddingWinJSControlsAndStyles references -->
        <link href="/css/default.css" rel="stylesheet">
        <script src="/js/default.js"></script>
    </head>
    <body>
    
        <p>Create a WinJS control in markup</p>
    
        <div id="ratingControlHost" data-win-control="WinJS.UI.Rating">
        </div>
    
    </body>
    </html>
    
    
  2. Your JavaScript code must call WinJS.UI.processAll to initialize the Rating control you created in the previous step. If you're using the Blank Application template, your default.js file already includes a call to WinJS.UI.processAll:

    
    (function () {
        "use strict";
    
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
        WinJS.strictProcessing();
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll());
            }
        };
    
        app.oncheckpoint = function (args) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // args.setPromise().
        };
    
        app.start();
    })();
    
    

    If you aren't using the Blank Application template or if you're adding the control to a page that you created yourself, you might need to add a call to WinJS.UI.processAll.

    • If you added the control to your app's home page (which is usually the default.html file), add a call to WinJS.UI.processAll in your onactivated event handler, as shown in the previous example.
    • If you added the control to a Page control, you don't need to add a call to WinJS.UI.processAll because the Page control does that for you automatically.
    • If you added the control to another page that is not your app's home page, handle the DOMContentLoaded event and use the handler to call WinJS.UI.processAll.
      
      function initialize() {
          WinJS.UI.processAll();
      }
      
      document.addEventListener("DOMContentLoaded", initialize(), false);
      
      

    The WinJS.UI.processAll function processes the document and activates any WinJS controls that you've declared in markup.

When you run the app, the Rating control appears where you positioned the div host element.

A rating control

Setting the properties of a WinJS control in markup

When you create an HTML control, you can set its properties using dedicated attributes. For example, to set the type, min, and max properties of an input control, you can set the type, min, and max attributes in your markup:


<input type="range" min="0" max="20" />

Unlike HTML controls, WinJS controls don't have dedicated element or attribute tags; for example, you couldn't create a Rating control and set its properties using this markup:


<!-- Not valid markup. -->
<rating maxRating="10" averageRating="6" />

Instead, you use the data-win-options attribute to set a property in markup. It takes a string that contains one or more property/value pairs:

data-win-options="{propertyName: propertyValue}"

 

This example sets the maxRating of a Rating control to 10.


<div id="ratingControlHost" data-win-control="WinJS.UI.Rating"
    data-win-options="{maxRating: 10}">
</div>

When you run the app, the Rating control looks like this:

Rating control shows a 10 star rating system.

To set more than one property, separate them with a comma:

data-win-options="property1Name: property1Value, property2Name: property2Value"

 

The next example sets two properties of the Rating control.


<div id="ratingControlHost" data-win-control="WinJS.UI.Rating"
    data-win-options="{maxRating: 10, averageRating: 6}">
</div>

When you run the app, the Rating control now looks like this:

Rating control shows a rating of 6 out of 10 stars.

If the property value is itself a string, enclose it in a different type of quote (' or ") than you used to set the data-win-options attribute. This example shows how to set the TimePicker control's current property, which takes a string:


<div id="timepicker" data-win-control="WinJS.UI.TimePicker" 
    data-win-options="{current: '10:29 am'}">
</div>

A TimePicker control showing the time at 10:29 AM.

To find out if a property is supported by a given WinJS control, see its reference page.

Retrieving a control that you created in markup

You can also set the properties of a WinJS control programmatically. To access the control in code, retrieve the host element and then use its winControl property to retrieve the control. In the previous examples, the host element of the Rating control is "ratingControlHost".



var control = document.getElementById("ratingControlHost").winControl; 


In some cases, you might want to retrieve and manipulate the control as soon as it's available. Be aware that the WinJS.UI.processAll method is asynchronous, so any code that follows it might run before WinJS.UI.processAll has completed. Given this, don't immediately try to manipulate the control because it might not be available :



WinJS.UI.processAll();

// Don't do this:
var control = document.getElementById("ratingControlHost").winControl; 
control.averageRating = 3; 
			


The WinJS.UI.processAll returns a WinJS.Promise object that you can use to call a function when the WinJS.UI.processAll method completes. Here the example defines a completion function that retrieves the control and sets its averageRating to 3.



// Do this instead:
WinJS.UI.processAll().then(function () {
    var control = document.getElementById("ratingControlHost").winControl;
    control.averageRating = 3; 
});

The next section describes how to add event listeners to a WinJS control.

Handling events for WinJS controls

Just like with HTML controls, the preferred way to attach event listeners for a WinJS control is to use the addEventListener function. Retrieving a WinJS control is a bit different than retrieving an HTML control, however.

To handle an event:

  1. In your JavaScript, retrieve the control's host element and use its winControl property to retrieve the control.
  2. Call the control's addEventListener function and specify an event and an event handler.

The next example shows how to handle the change event of a Rating control.

Hh465493.wedge(en-us,WIN.10).gifTo handle the change event of a rating control

  1. In your HTML file, add a paragraph and give it an ID of "outputParagraph". Your event listener will output to this paragraph.
    
            <p>Create a WinJS control in markup</p>
    
            <div id="ratingControlHost" data-win-control="WinJS.UI.Rating"
                data-win-options="{maxRating: 10, averageRating: 6}">
            </div>
     
            <!-- This paragraph will be used to demonstrate event handling. -->
            <p id="outputParagraph"></p>
    
    
  2. In your JavaScript, create an event handler function called ratingChanged that takes one parameter. This next example creates an event handler that displays the properties and values contained by the event object.
    
    
        function ratingChanged(event) {
    
            var outputParagraph = document.getElementById("outputParagraph");
            var output = event.type + ": <ul>";
            var property;
            for (property in event) {
                output += "<li>" + property + ": " + event[property] + "</li>";
            }
    
            outputParagraph.innerHTML = output + "</ul>";
    
        }
    
    
    
  3. Use the winControl property to retrieve the control from its host element and call the addEventListener function to add your event handler. This example retrieves the control as soon as it's created and adds the event handler:
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll().then(function () {
                    var control = document.getElementById("ratingControlHost").winControl;
                    control.addEventListener("change", ratingChanged, false); 
                }));
            }
        };
    
    

When you run the app and change the rating, it creates a list of event information properties and values.

The output from the change event.

Adding a WinJS control in code

The previous examples showed you how to create and manipulate a WinJS control that you created in your markup, but you can also create a WinJS control using JavaScript code instead.

Hh465493.wedge(en-us,WIN.10).gifTo create a WinJS control in code

  1. In your markup, create the element that will host your control.
    
    <div id="hostElement"></div>
    
    
  2. In your code (preferably in your DOMContentLoaded event handler), retrieve the host element.

    
    var hostElement = document.getElementById("hostElement");
    
    
  3. Create your control by calling its constructor and passing the host element to the constructor. This example creates a Rating control:
    
    var ratingControl = new WinJS.UI.Rating(hostElement); 
    
    

    When you run the program, it displays the Rating you created:

    A rating control created in code

    There's no need to call WinJS.UI.processAll—you only need to call WinJS.UI.processAll when you create a WinJS control in markup.

Summary and next steps

You learned how to create WinJS controls, how to set their properties, and how to attach event handlers.

The next topic, Quickstart: styling controls, describes how to use Cascading Style Sheets (CSS) and the enhanced styling capabilities of Windows Store apps using JavaScript. To learn more about specific controls, see the Controls list and Controls by function topics.

Samples

Related topics

Controls list
Controls by function
API Reference for Windows Runtime and Windows Library for JavaScript

 

 

Show:
© 2014 Microsoft