Hardware Access via JavaScript

Hardware access via web browsers is becoming integral of web technologies. Web technology platforms are used more to develop apps that live outside of the web. Faster browser release cycles has to helped bring hardware access to web browsers.

Portable devices now come with cameras, microphones, gyroscopes, GPS, light sensors and of course, the touch screen. Apps developed for the device have access to the device hardware.

But that hasn’t stopped the people creating web technologies to move forward to have access to the hardware. Now we can access hardware using JavaScript, HTML and CSS(somewhat)!

Below I will go over on some of the API’s that have access to your hardware.

GeoLocation

GeoLocation will read your location and return position coordinates, its longitude and latitude.

1
2
3
4
5
6
7
8
9
10
11
navigator.geolocation.getCurrentPosition(function(position) {
  console.log(position.coords.latitude, position.coords.longitude);
});

navigator.geolocation
navigator.geolocation.getCurrentPosition(success, error, options)
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;

id = navigator.geolocation.watchPosition(success, error, options);
navigator.geolocation.clearWatch(id);

Detect Device Orientation

The device orientation returns the values collected by the Gyroscope.

(orientation-1.js) download
1
2
3
4
5
// baseline example
// listen to events in deviceorientation
window.addEventListener('deviceorientation', function(event) {
  console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});
(orientation-2.js) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// More useful example
if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function( event ) {
  //alpha: rotation around z-axis
  var rotateDegrees = event.alpha;
  //gamma: left to right
  var leftToRight = event.gamma;
  //beta: front back motion
  var frontToBack = event.beta;

  handleOrientationEvent( frontToBack, leftToRight, rotateDegrees );
    }, false);
}

var handleOrientationEvent = function( frontToBack, leftToRight, rotateDegrees ){
    //do something amazing
};

To explain:

  • alpha – rotation of z-axis – how far the device is rotated around a line perpendicular to the device.
  • beta – rotation of x-axis – how far the device has tipped forward to backward
  • gamma – rotation of y-axis – how far the device has tipped left or right

Read More:

deviceOrientation (Mozilla)

Camera or Microphone Access

getUserMedia prompts the user for access to the media device.

1
navigator.getUserMedia(constraints, successCallback, errorCallback);
(getUserMedia.js) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
navigator.getUserMedia(
  // constraints
  {
    video: true,
    audio: true
  },
  //successCallback
  function(localMediaStream) {
    // select the 'video' object on the DOM
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);
    video.onloadedmetadata = function(e) {
      // let the video magic begin
    }
  },
  // error!
  function(err) {
    console.log("Oh noes, there was the following error:" + err);
  }
);

Read More

Battery API

The Battery API provides information about the systems battery. This can be used to measure the battery usage that your app is using. This can be used to manage your apps resources, what to trigger and what not.

(battery-api.js) download
1
2
3
4
5
6
7
8
9
10
11
12
13
var battery = navigator.battery;

var updateBatteryStatus = function() {
  console.log("Battery status: " + battery.level *100 + " %");

  if(battery.charging) {
    console.log("Battery is charging.");
  }
}

battery.addEventListener("chargingchange", updateBatteryStatus);
battery.addEventListener("levelchange", updateBatteryStatus);
updateBatteryStatus();

Read More:

BatteryManager

Vibrate

The method pulses the vibration hardware on the device. You can send a pattern for the vibration you want to trigger. The pattern alternates from the duration of the vibration and the pause.

1
2
// heartbeat pattern (short vibration (100), short pause(20), longer pause(500))
window.navigator.vibrate(100,20,100,500);

A fun way to implement it, is by synching it to transitions and animations on screen.

Read More:

Navigator.vibrate()

Ambient Light

Ambient light provides information from the phot sensors about the light levels near the device.

1
2
3
window.addEventListener('devicelight', function(event) {
  console.log(event.value);
});

A creative approach to the Ambient light, is to have a story adjust the mood depending on the amount of light in the room.

Touch Events

Touch Events are easy to overlook as hardware access since touch is the way we input on portable devices. Multi touch and gestures are exclusive input events to touch screens.

I’m not going expand here about touch devices, but you can read more about it: * W3 * Mozilla: Touch Events * hammer.js – JavaScript library with various touch events.

FileReader

A brief mention is being able to read the files on the device. Coremob Camera is an attempt to build a camera using web technologies.

More Reading

Web Components

Probably by now, you have heard of Web Components. Web Components are comprised of four different specifications ( Custom Elements, Templates, Shadow DOM and HTML imports). It’s a neat placed package of web technologies.

The goal of Web Components, is to organize and standardize best practices for web technologies. We all have seen or experienced how polluted a project can get when we start adding dependencies to it.

A Web Component is meant to keep things organized, to not conflict with the existing DOM and reduce the amount spent learning the code or API.

Some ideas of where Web Components would work:

  • Photo Carousel – <photo-carousel src="['pic1.jpg', 'pic2.jpg']"></photo-carousel>
  • Twitter Profile Card – <twitter-profile-card user="omar12" tweets="5"></twitter-profile-card>
  • Stripe Payment Form – <stripe-payment id="12345"></stripe-payment>
  • Disqus Comments – <disqus-comments short_name="awesomeblog"></disqus-comments>
  • Video Player – <my-video-player src="/web-technologist-log/path-to-video/videofile.mp4"></my-video-player>

SaaS companies can provide inhouse Web Components to their customers and have it running in no time.

In “Old HTML” terms, a Web Component is a JavaScript plugin on an iframe. We know that even has its limitations and it feels wrong in some way. But please, don’t think of them like that.

How to work with Web Components using Polymer

1.Download Polymer

We will download Polymer using Bower. If you haven’t heard of Bower, it’s basically a package manager for project dependencies. Find out more about Bower here.

1
2
3
bower init
bower install --save Polymer/platform
bower install --save Polymer/polymer

Read more about the installation here.

2.We add the following in the <head> of where you will include your Web Component.

1
2
3
4
5
6
7
<head>
  <!-- 1. Import the Web Components Polyfill -->
  <script src="bower_components/platform/platform.js"></script>

  <!-- 2. Import the Custom Elements-->
  <link rel="import" href="web-components/my-cool-element.html">
</head>

The 2 things to notice, is that we need to include the Polymer Polyfill.

3.Build your Polymer element.

Create an html file in the web-component folder.

(my-cool-element.html) download
1
2
3
4
5
6
7
8
9
10
<!-- Import Polymer -->
<link rel="import" href="../bower_components/polymer/polymer.html">

<!-- Define your custom element -->
<polymer-element name="my-cool-element" noscript>
    <template>
        <h3>My Cool Element</h3>
    </template>

</polymer-element>

You can include Custom Elements on other Custom Elements (cue Xhibit meme).

(my-super-cool-element.html) download
1
2
3
4
5
6
7
8
9
10
11
12
<!-- Import Polymer -->
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="my-cool-element.html">

<!-- Define your custom element -->
<polymer-element name="my-cool-element" noscript>
    <template>
        <h1>Super Cool Element!</h1>
        <my-cool-element></my-cool-element>
    </template>

</polymer-element>

Of course, the above is not a practical example, but something to manipulate or read data.

Right now, Web Components are partially supported on Chrome/Opera (Blink) and Firefox. No support on Safari or IE.

Keep an eye on it, Google and Mozilla are spending good amounts of energy behind Web Components, we can only hope more adoption of the technologies.

More Reading and Resources

Working With Flex

Flexbox (or flex layout) is a CSS box model optimized for user interface design. The child elements of a flex container have greater “flexibility” on how it is laid out on an HTML page. This means that it provides a simpler and more powerful tool for distributing space and aligning content for complex (or simple) layouts in web apps or web pages.

Using Flexbox can get your Responsive website layout working as intended.

Below is the barebones to get Flexbox going. The example is keeping the “Mobile First” approach.

View Demo

The following is a barebones example of the HTML:

1
2
3
4
5
6
<div class="flex--products">
  <div class="product">Product 1</div>
  <div class="product">Product 2</div>
  <div class="product">Product 3</div>
  <div class="product">Product 4</div>
</div>

First we define display: flex to the parent element that we want to hold the elements that will flex.

1
2
3
4
.flex--products {
  display: flex;
  flex-direction: row;
}

flex-direction: row will place each child element on its own row.

For wider viewports, we will switch the elements to be in its each column.

1
2
3
4
5
@media screen and (max-width: 46rem) {
  .flex--products {
    flex-direction: column;
  }
}

For the child elements, we define a flex: auto. flex: auto will automatically adjust the widths of the adjacent elements.

1
2
3
4
5
6
.product {
  flex: auto;
  padding: 1rem;
  margin: .1rem;
  background: $product-color;
}

Full SCSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$midnight-blue: #2c3e50;
$belize-blue: #2980b9;
$white: #fff;

$bg-color: $midnight-blue;
$product-color: $belize-blue;

body {
  background: $bg-color;
  color: $white;
  padding: .5rem;
}

.flex--products {
  display: flex;
  flex-direction: row;
}

.product {
  flex: auto;
  padding: 1rem;
  margin: .1rem;
  background: $product-color;
}

@media screen and (max-width: 46rem) {
  .flex--products {
    flex-direction: column;
  }
}

Below you will find more Flexbox resources:

Reading

Code

Sandboxes

Technical

The Web Technologist Log

Web Technologies are in a continual enhancement. We see new API’s that bring different visual, performance or hardware information features.

The log will be a collection of any upcoming browser features. It will describe how it does, a code sample of how it should work, a working example and any external resources available.