Share via


Quickstart: Adding WinJS controls and styles (HTML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

The Windows Library for JavaScript (WinJS) provides high quality infrastructure such as page controls, promises, and data-binding; polished UI features like virtualizing collections; and high performance Windows controls such as ListView, FlipView, and SemanticZoom.

You can use Windows Library for JavaScript in your Windows Runtime apps, in your websites, and when using HTML-based app technologies like Apache Cordova.

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

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 easier to develop great-looking apps. WinJS includes objects that help you handle activation, access storage, and define your own classes and namespaces.

  • For the complete list of controls that WinJS provides, 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 the latest version of WinJS in your app or website:

  1. Download the latest version from Get WinJS and copy it to the directory for your app or website.
  2. Add WinJS CSS and script references to each page of your app or website that uses WinJS features.

This example shows what these reference look like for an app that has its WinJS files in its root directory.

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

    <!-- WinJS code -->
    <script src="/WinJS/js/WinJS.js"></script>

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 Microsoft 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="/WinJS/css/ui-dark.css" rel="stylesheet">
        <script src="/WinJS/js/WinJS.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 apps using JavaScript. To learn more about specific controls, see the Controls list and Controls by function topics.

Samples

For live code examples of nearly every WinJS control and an online editor, see try.buildwinjs.com.

Get WinJS

Controls list

Controls by function

API Reference for Windows Runtime and Windows Library for JavaScript