Website & App Accessibility for the Visually Impaired

The internet is an important and mandatory part of modern life, including the 285 people million worldwide who have some form of visual impairment (1.4 billion web users worldwide have accessible needs). However, those with visual impairments are often unable to use much of the internet as many sites demand that lack features necessary for low or no vision users. The lack of sight isn’t the only issue as approximately 8% of the male population experiences one of the three forms of color blindness. Visually impaired users comprise of a large segment of the population, usually around 10%. It’s important to provide an accessible site so that you can reach all your customers without inadvertently adding challenges for some. Additionally, there are laws that US government websites as well as websites at some companies or sectors must adhere to defined by http://www.section508.gov/. Before jumping into the technical aspects of accessibility, let’s look at how visually impaired users “see” your web pages.

How the Visually Impaired Use the Internet

The internet is largely visual, and that can exclude people who have visual impairments from accessing its contents. Low vision users often require the use of assistive technology, usually in the form of a screen reader. While most people need to increase the browser’s font size frequently, those with severe impairments must use a screen reader such as JAWS, NVDA, Window Eyes, or one of the many others. If you’ve never used a screen reader, you can watch this video about how a blind student uses the internet that should give you a sense of what it’s like. Screen readers are quite robust in their capabilities, but they do have limitations, and cannot completely substitute for the visual experience, especially in a graphic laden site. That’s because screen readers cannot read videos or image data, only textual data and DOM elements. Additionally, low vision and blind users rely heavily on using the keyboard, since a mouse demands high fidelity eyes as well as hands to work. That means non-mousers use Tab/Shift keyboard combination in a Windows system to move between heading level tags, named anchors, and form elements, sometimes while waiting for the reader to catch up. This is the opposite of a sighted person who’s eyes can quickly scan away from redundant menus or ads to get to the good content.

Others may have a contrast sensitivity rather than, or in combination with, low or no vision. When one has a visual issue that affects contrast, the eye has reduced ability to distinguish between similar shades and levels of brightness. That makes the experience of color different from that of what we classify as normal vision. In fact, the popular social networking site Facebook uses color code #3b5998 (dark blue), because its founder Mark Zuckerberg is colorblind. Eye diseases such as Retinitis Pigmentosa, Retinopathy, Cataracts, and Glaucoma all lead to sharp decreases in contrast and/or color sensitivity. The colors actually look different to folks with contrast sensitivities. What you see as red might look brownish or even gray to someone else. This article at MSDN reveals how users with varying colorblindness and contrast sensitivities see web pages.

Accessible Content and Design

When building accessible web pages, we can do many things that will enable their usage for people with assistive technology. The first and easiest step to take in creating visually accessible web pages is to increase the default font size! Most of the citizens of the world do not have 20/20 vision, so increasing the font size is a tremendous gain with only a single line of code to change in the site’s default CSS file. When crafting hyperlinks be sure to set the link text (i.e., the text between the anchor tags) to something descriptive that matches the link target. Avoid generic text such as the words “Click here”, and be sure to include a complete description of what the user can expect on the other side of the link. Applying the name attribute to anchor tags means users can use the keyboard to skip through to that hyperlink.

Two colors that have low contrast might be fine to someone with normal vision, but it is likely harder to distinguish between the colors, letters, and symbols for someone who is colorblind. Quite possibly the most important design concept for accessibility is to keep the site clean of clutter, and navigable with alternative methods of input than a mouse. You can ensure your color schemes and contrast work well by visiting these sites: http://webaim.org/resources/contrastchecker/ and http://www.checkmycolours.com.

Screen readers must read everything on the page they can access (usually DOM and text), and that includes headers and footers that show on every page in the website. It can take several minutes to plow through a menu that a sighted user can scan in just one second. To remedy this, we use Skip Links. Skip links are HTML anchros that allow the speech software or braille user to bypass redundant information, such as navigational menus. Speech and braille users generally read the page from top to bottom,  and consequently are subjected to repeated information before reaching the heart of the page. All you need are two lines of code. Just put an anchor before the repeated HTML (usually a menu), or right at the beginning of the page, like this:

<a href=”#content”><img src=”empty.gif” height=”15″ border=”0″ alt=”Skip Main Navigation” width=”5″></a>

Then place a named anchor at the beginning of the unique content, where the reader’s eyes would normally skip to:

<a name=”content”></a>

Then you have a skip link. This tag can exist anywhere in the page that you think the screen reader should land, so it can continue reading from there. Adding something as simple as skip links in your source enables the machine reader to save a significant amount of time on behalf of the user. Check out the skip links at WebAIM. They work perfectly.

Accessible HTML Layout and Elements

You can craft accessible HTML with little to no extra effort than you normally use in your daily development tasks. Simple things like using header tags, <h1> through <h6>, make the page navigable via keyboard, as low vision users may have difficulty seeing where to mouse. Avoid using <div>, <span>, or <p> tags with larger fonts, as they don’t allow for keyboard navigation or work well with assistive technologies. Besides, <h1>-<h6> are meant for headings. When displaying media, each <img> element must have clear and succinct alt attribute value, as this is the only way assistive technology such as screen readers and braille machines can convey what is inside the image. This is an easy coding task. When laying out sections of pages with HTML <tables>, be sure to include the <th> elements for navigation and assistive technology, rather than using <td> tags for column headings.

The Web Accessibility Initiative established WAI-ARIA, the Accessible Rich Internet Applications Suite, as a way to make Web content and sites more accessible to people with disabilities of any sort that makes computing unnecessarily difficult. WAI-ARIA published a set of standard attributes so that HTML can integrate with assistive technologies.

Many popular websites, especially news sites, will be disheartened to hear that JavaScript cascading menus and JavaScript popup ads (jQuery lightboxes) make it an order of magnitude harder for low vision and blind users. Often, ads fly in from the top, bottom, and sides of a page, and march across the screen making it impossible for assistive technology to translate what’s going on to the user. Screen readers and braille machines can’t do their jobs properly under these conditions. When this happens, low vision users must leave the site as it becomes simply unusable. Considering the numbers of visually people internet is 10% of your user base, you’re turning away a big chunk of your user base just by using popups. There are better ways to advertise.

Accessible HTML Forms

Submit and reset buttons as well as the <button> element automatically work with assistive technology. You must make some minor modifications to other form elements though. Using the <label> element is a very effective way to enable screen readers and braille machines to present the text and meaning of any HTML input tag. When building HTML forms in general, be consistent with the placement of labels and input fields, and be sure to explicitly state required fields and validation. While it is a common practice to indicate which items are required fields with a non descript red asterisk or icon, it is not very accessible. Adding the word “Required” or a precise description of the validation message to the label makes validation rules clear to readers and devices. Label all input elements of the form. Below is a sample of the proper way to label for accessibility:

<label for=”fullName”>Full Name </label><input id=”fullName” type=”text” />

Notice that the <label>’s for attribute matches the <input>’s id attribute. Without this connection, visual assistants cannot determine which labels belong to which element. When working with dropdowns, label the entire dropdown as well as each individual item in the dropdown by placing text between the <option> elements.. 

<label for=”favoriteLanguage”>Choose your favorite programming language:</label>
<select id=”favoriteLanguage” name=”select”>
    <option value=”1″>C#</option>
    <option value=”2″>VB</option>
    <option value=”3″>JavaScript</option>
    <option value=”4″>Ruby</option>
    <option value=”5″>Lisp</option>
</select>

Checkboxes only need that you use the <label> element, and they’ll work with readers. The American Association of the Blind recommends avoiding Radio buttons, stating that many of the assistive programs out there do not support them well. Since radio buttons often represent simple binary data or yes/no answers, a checkbox should work fine as an alternative. You can move to a drop-down for three or more items.

<label for=”yesNoAnswer”>Is C# your favorite language?</label><input id=”yesNoAnswer” type=”checkbox” />

In addition to open standard HTML, the WAI-ARIA standards provide ARIA tags that you can use to enhance assistive technologies, especially in HTML forms. You can apply the aria-label attribute to elements that have no text, such as an image or a submit button. Form elements that you require the user to fill in should have the aria-required attribute set to “true”. Our previous example that creates a text box to contain a full name can be expanded like this:

<label for=”fullName”>Full Name </label><input aria-label=”Full Name” aria-required=”true” id=”fullName” type=”text” />

It’s not just HTML elements that affect accessibility. While it’s a common practice to set the cursor’s focus to a starting field with JavaScript in HTML forms, doing so interferes with screen readers. The same goes for AJAX scripts that run upon form submissions. Having client side scripts are Ok as long as you don’t forget to test the pages to make sure they work with the keyboard as well as assistive technology, and do not intrude on the user’s workflow. You can read more in depth about techniques for HTML form accessibility at WebAIM online.

Conclusion

The American Association of the Blind has many resources for creating visually accessible web sites. Hide your mouse away while testing web pages to force yourself to be a keyboard user, and test for harmony with assistive technology. You can do so by trying out a few of these 10 free screen readers, or the Web Anywhere browser based screen reader that requires no software installation. Before you publish your web site check out the Web Accessibility Evaluation Tool (WAVE). This tool lets you plug in a URL and it will show that same page with annotations specifying its level of accessibility compliance. Finally, Microsoft has released an Accessibility Center where you can learn about various development techniques and tools to help you reach all of your customers.

Use SignalR to Build Real-Time Connectivity into Your Software

You want to write software that works just like popular social networking sites do, with lively, immediate information. That means building real-time high-frequency updates into your software, because users want their data and they want it now. In some situations, moving data in real-time is essential to the success of the app as it gives an upper hand to the business that does so. Not just that, but let’s face it – it’s cool to be the developer who writes the high tech websites. If you want to build these modern websites and apps with live, two-way communication, then SignalR is something you should seriously consider.

What is SignalR and why should you use it?

SignalR is a set of libraries that facilitate easy development of these kind of real-time websites and apps. It is open source, and you can get it here: GitHub. It works across all the major platforms. SignalR the newest member of the ASP.NET family, that enables developers to write incredibly simple real-time, two-way websites and apps. Two-way communication means that both the server and client share an open channel in which they can initiate contact with each other.  This channel is high-speed and works both directions between server and client. Many kinds of software can benefit from the real-time, two-way, communication system of SignalR. They include high traffic finance and stock apps, auctions, voting, quizzes and polls, lotteries, games, and many more. If your app’s not in the list, you still might want to investigate Signal, as UXs with high-frequency updates tend to be the ones that the users prefer (and rate higher for those in app stores).

SignalR is built to the OWIN specification. OWIN, short for Open Web Interface for .NET, is a set of standards for constructing a pluggable, modular, Web server architectures. Fortunately as SignalR developers, we don’t really need to dig into the specs to write SignalR code, most of the time.

Conceptually, SignalR works like a hub and spoke, or hubs and clients, as we call them. This means that the client can call the server, like we normally see in a HTTP Request-Response model, but now the server can contact the client, and one client can contact other clients (through the server). This is not the kind of programming that web developers usually do. SignalR contains two primary components: Hubs and Clients. Hubs, as you might expect, are server side and they behave a lot like super fast switchboard operators (oxymoron?). Clients, on the other hand, behave the same, except that now they can also receive calls from the server. This is where SignalR differs from customary Web programming, in that both sides can initiate communications between each other once the client initially opens the pipeline.

SignalR uses Websockets technology everywhere that it possibly can, and when it’s not possible, it uses an algorithm to determine the best possible transport. It supports the following transports: WebSockets, Long Polling, Server Side Events, and Forever Frame. As developers, we barely need to know cursory information about these frameworks to benefit from SignalR.

Get Started With SignalR Development

Since SignalR is an ASP.NET product, we’ll need to create an ASP.NET project in Visual Studio (unless you self-host, but we’ll stick with ASP.NET here). You can go with either Web Forms or MVC, as SignalR is also ASP.NET, and it all works together. Then install the “Microsoft ASP.NET SignalR” package into the ASP.NET project, using either the GUI or the Package Manager console. When you install the generic “Microsoft ASP.NET SignalR” package, it installs a few dependencies. Those are both server and client side components that work in tandem so that SignalR can do its thing. You can verify the installation by checking for references to Owin under the project references and jquery.signalr-2.0.3.js and similar files under the Scripts node in Solution Explorer.

Every site needs a starting point, and for SignalR apps, we need to hook into the OWIN pipeline of modular architecture. That means that we need to run a quick bit of code during startup. To do so, put the following code in a class in App_Start. This tells ASP.NET that the SignalR OWIN modules will be part of the regular IIS pipeline. Below is sample startup code for a voting app. The app loads several images and allows users to vote on one or more items.

[assembly: OwinStartup(typeof(VoteR.App_Start.Startup))]

namespace VoteR.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Once we insert the startup code, we can move to our centerpiece of activity, the hub.

Hubs

Hubs enable developers to write code to accept calls from clients and call methods on clients. When many people are voting, the action happen incredibly fast, so it’s a perfect candidate for real-time connectivity. Not to mention that users want to see the vote total updating in real time. Let’s see this in action by examining the VoteHub class. The VoteHub class inherits from the Microsoft.AspNet.SignalR namespace. In this class is the Vote public method that that the clients can call, and when they do, it is syntactically similar to an ASMX Web Service call, meaning that it uses standard dot notation (see the Clients section of this post). The private AddVote method is just a method that public
or other private methods call. It accesses some static members to track which client has the highest bid.

public class VoteHub : Hub
{
    private static List<Item> VoteItems = new List<Item>();
    private static VoteRContext db = new VoteRContext();

    public void Vote(int id)
    {  
        // AddVote tabulates the vote        
        var votes = AddVote(id);
        // Clients.All.updateVoteResults notifies all clients that someone has voted and the page updates itself to relect that
        Clients.All.updateVoteResults(id, votes);
    }
    private static Item AddVote(int id) {

        // If the item is in VoteItems, we’re tracking it, so just increment and return
        var voteItem = VoteItems.Find(v => v.Id == id);       
        if (voteItem != null)
        {
            voteItem.Votes++;
            return voteItem;
        }
        // If the item wasn’t in VoteItems, it’s the first time someone voted for it.
        // Add it to VoteItems and increment from zero
        else
        {
            var item = db.Items.Find(id);
            item.Votes++;
            VoteItems.Add(item);
            return item;  
        }    &nb
sp;  

    }
    public override Task OnConnected()
    {       
        // Send voting history to caller only so they can see an updated view of the votes  
        Clients.Caller.joinVoting(VoteItems.ToList());
        return base.OnConnected();
    }
}

Any custom public method (not overrides) in that you add to your Hub class is callable via dot notation from the client, via a special property. Notice that in the above code sample that there is no need to write code to deal with concurrency or transport negotiation, SignalR does it all for you.

Something that is a bit different from standard web development are the calls to Clients.Caller.joinVoting and Clients.All.updateVoteResults. By accessing the Clients property of the Hub class, we can effectively use that open pipeline to call the joinVoting and updateVoteResults methods on the client using dot notation. You can pass simple or complex arguments, as shown in the code above. SignalR does all the serialization of objects such as the List<T> automatically. Let’s see how to define these methods on the client in JavaScript and how SignalR connects Hub and Client code. The Clients property of the Hub contains the following methods: All, AllExcept, Client, Caller, Group and a few other methods that you can use to send messages to specific clients or groups of clients through the Hub. This gives you a granular way to deal with client-client connectivity.

Clients

When using ASP.NET MVC, we can render some the data on the server in Razor views, and add JavaScript for rich client interactions. Below is a Razor view that loops through an IEnumerable<VoteR.Models.Item> object rendering the name, image, number of votes, and a voting button. After every 4th item, the loop moves to the next row. The <script> tags render at the end of the page. Default.js contains SignalR code that votes on behalf of the user and updates the screen with the current number of votes. Because SignalR is real-time, the current number of votes will be up to date. None of the ASP.NET MVC code is different than we normally write. This is a plain MVC view. We’ll use JavaScript to take data from the view and send to the server.

@model IEnumerable<VoteR.Models.Item>
<h2>Vote!</h2>
<table>
    <tr>
        @{var i = 1; }
            @foreach (var item in Model)
            {
                <td style=”border:1px solid #000; width=”200px”>
                    <h4>@item.Name</h4>< /span>
                    <div><img src=”@Url.Content(item.Image) width=”125″ height=”125″ /></div>
                    <h4>Votes: <span data-itemid=”@item.Id“>0</span></h4>
                    <button id=”@item.Id“>Vote For This</button>
                </td>
                if (i % 4 == 0)
                {
                    @:</tr><tr>
                }
                i++;
            }
        }
    </tr>
</table>

@section scripts {
    <script src=”~/Scripts/jquery-1.10.2.js”></script>
    <script src=”~/Scripts/jquery.signalR-2.0.3.js”></script>
    <script src=”~/signalr/hubs”></script>
    <script src=”~/Scripts/default.js”></script>
}

With script, we first must obtain a connection to the VoteHub and store it in the voteHub variable. Notice the syntax , $.connection, is a static reference. This is a proxy that SignalR automatically creates for us at the /signalr/hubs location. You need do nothing special for the proxy to work.

In the JavaScript below, in the assignment of voteHub property, the $.connection.voteHub part might look like a typo, but SignalR uses camelCasing on the client following popular JavaScript notations. This means that the default manner in which you reference the VoteHub class is voteHub. You can change this by adding the HubName attribute to the Hub class (server side) and specifying the exact name and case of the class, like this: HubName(“VoteHub”). The it changes the proxy to reflect the casing.

After obtaining a connection to the hub, we must start the hub if it isn’t already started. This is a good time to wire up any events such as click events where you’ll be calling hub methods. After wiring up calls to the hub, it’s time to declare methods that the server will call. In the example below, these methods are voteHub.client.joinVoting and voteHub.client.updateVoteResults. Notice their declaration uses the hub.client.method syntax, hanging the methods off of the client property of the reference to the hub. To call code on the server, just use the server property of the client side hub object. In this case, that is voteHub.server.vote. The code passes the value of this.id to the method. “This”, in this case is the button containing the ID of the item the user is voting for.

$(function () {
    var voteHub = $.connection.voteHub;
   
    $.connection.hub.start().done(function () {
        $(“button”).click(function () {
            voteHub.server.vote(this.id);
        });
    });

    voteHub.client.updateVoteResults = function (id, vote) {
        var voteFor = $(“span[data-itemid='” + vote.Id + “‘]”);
        voteFor[0].textContent = vote.Votes;
    }

    voteHub.client.joinVoting = function (votes) {    
        for (i = 0; i <= votes.length – 1; i++) {
            var voteFor = $(“span[data-itemid='” + votes[i].Id + “‘]”);
            voteFor[0].textContent = votes[i].Votes;
        }
    }
});

When a new user connects, the OnConnected method in the Hubs example calls the client side joinvoting and passes in voting history. This way the new voter is current, as joinVoting also displays all the information about all the votes in progress. Examining either the voteHub object or Hub class, you’ll see the server and Clients properties. These are the properties that enable the two-way real-time communication between the hub and the client. All you do is attach public methods to them and make the calls using the hub.server.method syntax. Finally The updateVoteResults method does the UI update, so each item’s <span> element displays how many votes it has.

Conclusion

There are many kinds of websites and apps that can benefit from SignalR’s real-time, two-way, communications model. Perhaps a stockbroker needs financial information to buy the right stock at the right time and get a promotion. Or maybe someone is building the next big thing in social networking and the “likes” need to happen right away. That high-action game that everyone is addicted to needs to be in real-time or people wouldn’t enjoy it as much. If it’s an app, enjoyment and a rich experience translate directly to ratings, which in turn translates to more visibility and revenue.

While in this article I’ve only mentioned Hubs and clients, there is lower level of abstraction that SignalR offers called a Persistent Connection. If you, for whatever reason, need to perform more of the lower level tasks regarding connection management, the PersistentConnection class is what you’d use. If you check out the members of the PersistentConnection class, they look a lot like the Hub class but with more members regarding connectivity. It gives you more gr
anular control, but for most scenarios, hubs and clients will work just fine.

Download sample code: https://github.com/rachelappel/VoteR 

Resources:

ASP.NET SignalR

SignalR.net

Scott Hanselman on SignalR

Use the W3C Geolocation API to create location aware web sites

Location aware services and applications are becoming more important than ever before, as smartphones, tablets, and other fully featured mobile devices become ubiquitous. The W3C Geolocation API gives developers an easy way to integrate client side location aware services within their web pages.

Hello, location aware world!

With the advent of geolocation services and mapping APIs, web sites and applications are popping up daily providing the following types location aware software:

  • Games and social applications, (e.g., Foursquare, Twitter, Trip It, Facebook, etc…)
  • Search applications for local services (e.g., restaurants, shops, entertainment, etc…)
  • Navigation & maps
  • Package shipping/tracking & transportation services
  • Personal health & fitness
  • More…

Notice there’s a good mix of both business and consumer applications that benefit from using geolocation. Fortunately, for developers, location aware web sites and apps are easy to create with web standards like HTML5, JavaScript, and CSS. On top of that, APIs like Bing  or Google Maps make great companions to these sites – and don’t forget 3rd party APIs such as Foursquare or Yelp.

How location aware web sites work

Geolocation apps work by detecting the user’s location via positional data that it receives from a geolocation source.

There are three basic steps to the process:

  1. The client browses to a web page that attempts to access the geolocation source.
  2. The app requests permission to send access the geolocation source.
  3. If the user permits, the app or web site can access and use the user’s positional data. (If not, an error occurs. See below

Once you have obtained the user’s coordinates from the API, you can display maps, give directions,show nearby points of interest

However, keep in mind that the device is the deciding factor regarding the accuracy of the positional data. For example, using a 3G smart phone should yield more accurate results than a desktop machine that connects through an ISP a mile away, using an IP address based method. Devices can use one or more of these methods:

  • Coordinate triangulation
  • Global Positioning System (GPS)
  • Wi-Fi with MAC addresses from RFID, Wi-Fi, and Bluetooth
  • IP address
  • GSM or CDMA cell phone IDs
  • Custom sources: Some phone manufacturers like Nokia

Many smart phones provide a way for users to switch between sources such as 3G or WIFI.

Obtaining the user’s positional data using the HTML5 Geolocation API.

For creating web sites either straight-up JavaScript or jQuery will work fine with the geolocation API. It’s quite small, with only three methods:

Method Description
clearWatch Stops listening for updates to the current geographical location.
getCurrentPosition Obtains the geographic position, in terms of latitude and longitude coordinates.
watchPosition Begins listening for updates to the current geographical location of the device running the client. Use this method to listen for location updates.

Before obtaining the user’s coordinates, a call to Modernizr performs feature detection for geolocation support. If the browser supports geolocation, the code calls the watchPosition() method, and passes success and error callback methods as arguments. Below is the code sample outlining  the call to watchPosition().

$(function () {
    var watchID;
    $("#watch").click(function () {
        if (Modernizr.geolocation) {
            var nav = window.navigator;
            if (nav != null) {
                var geoloc = nav.geolocation;
                watchID = geoloc.watchPosition(successCallback, errorCallback);
            }
        }
        else
        { $("#message").text("You'll need to enter your address manually."); }
    });   
});

A successful completion of the watchPosition() method triggers the successCallback() method. At this time, the code can access the positional data returned from the Geolocation service in order to display Bing maps, list nearby attractions, or whatever is required. Below shows code that obtains the user’s coordinates, then displays the latitude and longitude in a web page <div> element (<div id=”message”>). Notice that the position argument  is populated with data, however not all the properties will contain values (e.g., altitude), depending on the capabilities the device and service.

function successCallback(position) {
 
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
 
    $("#message").text("There you are at " + latitude + " " + longitude);
}

Of course, the code won’t always run successfully. There are many things that can get in the way: bad weather, permission denied, timeouts, no cell reception, and gremlins, to name a few.

Dealing with errors and timeouts

The errorCallback() function does what you might expect, it runs when an error occurs. There are three frequently occurring errors to look for when the errorCallback() executes:

  1. PERMISSION_DENIED
  2. POSITION_UNAVAILABLE 
  3. TIMEOUT

A switch statement works nicely to determine the error source and take corrective action, as each case checks value in the error.code property against a set of constants that correspond to error numbers.

function handle_errors(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED: 
            alert("User did not share geolocation data");
            break;
        case error.POSITION_UNAVAILABLE: 
            alert("Could not detect current position");
            break;
        case error.TIMEOUT: 
            alert("Time out");
            break;
        default: 
            alert("Unknown error");
            break;
    }
} 

 

Summary

Location aware web sites are becoming more important than ever before, and since the W3C Geolocation API is a standard, it works with any technology ranging from plain HTML to ASP.NET.

To get started creating location aware sites, check out the following resources:

W3C Geolocation Introduction

Geolocation APIs & client side frameworks on Code Project

JavaScript Strict Mode Explained

JavaScript is everywhere. It’s run in web sites, as utilities on many operating systems, and in any host, like IE, Firefox, or Chrome and it’s a first class citizen in Windows 8 Metro style app development. Since JavaScript has been around for a long time, it still has a lot of baggage from when it was immature. Because of this, Strict Mode has become a feature in ECMAScript 5, or ES5 (JavaScript).

What is Strict Mode and why use it?

Because Strict Mode is ECMAScript, it is a standard, and a best practice, and highly recommended that you use it. In the future, Strict Mode will be your only choice, which is certainly for the best. Strict Mode offers up these enhancements to the JavaScript language:

  • JavaScript throws errors if you try to use deprecated language elements
  • Variable declaration is mandatory
  • Disallows duplicate property and parameter names
  • The eval() method is safer to use, but still considered evil in some cases.
  • Deprecates the with statement
  • JavaScript throws errors if you try to assign a value to a read only property
  • Decreases the global namespace pollution

Most ES5 compliant JavaScript runtimes support Strict Mode, and you can get full details at this in-depth article on Strict Mode at MSDN.

Where can I use Strict Mode?

You can use strict mode in any JavaScript host or engine that supports ES5 standards, and specifically, Strict Mode. Check out this comprehensive ES5 Compat Table on Github to see if your browser supports strict. You will see a lot of green lights, so there is wide support across browsers. This means if you are a web developer you can start using Strict Mode today.

If you are a Windows 8 Metro style apps HTML/JS developer, Strict Mode is automatically added to the project templates in Visual Studio 11 as WinJS supports Strict Mode.

Enabling Strict Mode

Applying Strict Mode is very easy to do. Just add the “use strict” directive to your code (it’s a string literal so include the quotes). The physical location of the strict directive determines the scope of Strict Mode. Below is a table showing the relationship between Strict Mode and scope. This means you can turn Strict Mode on and off granularly in code.

Code location Scope
Beginning of any .js file Global
Beginning of the script inside a <script> element. <script> element
Preceding function block
First line in function block
Function

As you can see, Strict Mode is flexible but try to keep Strict Mode out of a global setting where possible when dealing with Web pages (HTML, ASP.NET, PHP, etc…). If other scripts include your script using Strict Mode, then Strict Mode could apply to the included scripts and that can create problems. However, you can get the same effect as global Strict mode by wrapping your code like so:

$(function () {
    “use strict”;
    function strictFoo() {
        alert(“I am in strict mode”);
    }
    function strictFoo2() {
        alert(“Me too!”);
    }
});

This creates a block around both functions and Strict Mode appears global to to the all code that exists in that block, essentially making strict container for that code. 

Summary

Strict Mode is great because it catches common programming ID10T errors. These are the kind of errors everyone makes, regardless of experience, and often because of experience. It’s very easy, especially when moving from a compiled language, to miss some of the finer nuances of JavaScript. Strict Mode helps smooth out those JS language kinks.

Write Object-Oriented JavaScript with TypeScript

TypeScript, Microsoft’s new language, is proving to be a popular choice amongst ASP.NET and Windows developers. Of course, those coming from the Microsoft stack are used to working with Object Oriented languages, except with significantly differing syntaxes. TypeScript brings familiar OOP constructs to JavaScript. TypeScript is not a new language as it is a superset of JavaScript that generates plain JavaScript. There are four main principles to Object Oriented Programming: Encapsulation, Inheritance, Abstraction, and Polymorphism. TypeScript can implement all four of them with its smaller and cleaner syntax.

For a primer on TypeScript, read TypeScript, A New Language For .NET & JavaScript Developers.

Encapsulation

Encapsulation is a key part of Object Oriented Programming that is a way to structure code so that a certain block of code has specific access points for external code. The term for this is “visibility” or “accessibility”. Visibility defines what code from one method, property, or class can call code in another method, property, or class. In other words, if we were to interact with a real world object like a car, we do so by using only certain parts of the car that are there for that purpose. These components of the car communicate to parts inside the car that perform the actions on our behalf. In the case of a car, these external parts are the pedals, steering, and dashboard controls, while the internal ones are in the engine. This means we don’t need to know what goes on under the car’s hood to make the car go, stop, or turn, all we need to do is interact with the correct component, called an interface. (i.e., the pedals, steering, dashboard controls). To enforce encapsulation in many languages, we use methods and properties. Both are blocks of code, although they differ mostly in syntax rather than conceptually. Behind each method or property is logic that often hides private data and performs complex tasks. The calling code shouldn’t and doesn’t need to know about those things.

In TypeScript, we enforce encapsulation with methods and properties that only allow access to data that we control. The Withdraw method below does that by doing the calculation and updating the class level _balance field. The Balance property then returns the private _balance field to the calling code.

Withdraw(amount: number): boolean
{
    if (this._balance > amount)
    {
        this._balance -= amount
        return true;
    }
    return false;
}

private _balance: number;
get Balance(): number {
    return this._balance;
}

This encapsulates the account’s balance as business logic and validation code can run and access the private variables to formulate something to return to the client. In turn, the client never needs to know what goes on behind the scenes, just how to interact with the object. TypeScript’s syntax is similar to that of a statically typed language like C#, by using constructs like setters and getters.

Inheritance

It’s quite easy to create an object model and inheritance chain with TypeScript. Just start with the familiar class keyword to create classes. The extends keyword causes the child class to inherit from the denoted base class. For example, we can build out a very simplistic SavingsAccount and CheckingAccount classes that derive from a BankAccount class, like so:

module Bank {
    class BankAccount { }

    class SavingsAccount extends B
ankAccount { }

    class CheckingAccount extends BankAccount { }
}

The two above TypeScript samples generate the JavaScript below. It’s very clear in TypeScript sample above that inheritance is happening, but not as clear in straight up JavaScript sample below. Sure, you could write this yourself, but as you can see, TypeScript generates the code you’re supposed to write, but without all the typing involved. There are only three lines of code needed for Bank class, but thirty for JavaScript. That’s a difference of ten times as much.

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Bank;
(function (Bank) {
    var BankAccount = (function () {
        function BankAccount() {
        }
        return BankAccount;
    })();

    var SavingsAccount = (function (_super) {
        __extends(SavingsAccount, _super);
        function SavingsAccount() {
            _super.apply(this, arguments);
        }
        return SavingsAccount;
    })(BankAccount);

    var CheckingAccount = (function (_super) {
        __extends(CheckingAccount, _super);
        function CheckingAccount() {
            _super.apply(this, arguments);
        }
        return CheckingAccount;
    })(BankAccount);
})(Bank || (Bank = {}));

TypeScript classes make it easy to map properties to JSON or XML data, common in web sites and apps. Looking at the above sample, you can see that it does adhere to the module pattern. TypeScript supports single inheritance.

Abstraction

There is no formal mechanism for creating an abstract class in TypeScript, although a request to implement abstraction in TypeScript has been issued. Not to worry, for now we can use interfaces as a way to abstract class members. For example, a bank might have an Fee interface
(their favorite one!) or an Interest interface that all account objects must implement. The Fee interface has members such as ChargeFee and the Interest interface contains one named CalculateInterest. When classes implement these interfaces, they must implement all of the members of the interface, as interfaces serve as digital contracts that classes can adhere to.

You can use the implements keyword to implement an interface in TypeScript, as shown here:

export module Bank
{
    export interface Fee { ChargeFee(amount: number); }

    export class BankAccount implements Fee {
        ChargeFee(amount: number) { }
    }
}

It’s syntactically like the extends keyword.

Polymorphism

TypeScript enables polymorphism via method overrides as you can see in the example below. The Withdraw and Deposit methods of the CheckingAccount and SavingsAccount classes derive from the parent BankAccount class. In the child classes, we can override these methods and add our own business logic customizations, such as waving a fee if the balance is more than a specified amount.

class SavingsAccount extends BankAccount
{
    ChargeFee(amount: number)
    {
        if (this.Balance > 1000) { amount = 0; }
        else { amount += 1.00; } 
         
        this.Balance =+ amount;
    }
}

In this case, we overrided the ChargeFee that was originally part of the Fee interface. Polymorphism is an essential characteristic of OO programming, as code would be quite redundant without it.

Summary

As you can see, TypeScript enables all four of the primary object oriented programming techniques with easy to use keywords and syntax. TypeScript is a bit of a syntactic sugar sprinkled on top of JavaScript, and it fits in many developer scenarios since OOP is such a popular and reigning paradigm. Using TypeScript doesn’t mean you’re off the hook of knowing JavaScript well – the better you know JavaScript is the better you’ll know TypeScript.

To see how you can apply the OOP principles of TypeScript in Windows Store apps, check out my article on MSDN Magazine about Using TypeScript in Modern (Windows Store) apps and my blog posts tagged as TypeScript.