10 things you didn't know JavaScript could do
You can do all kinds of crazy stuff with JavaScript. Developer Sebastian Golasch show us what's possible today: gamepad-controlled 3D games, Flash on the iPad, running a webserver, and more...
JavaScript has gone a long way since its birth in 1995. A hard way for sure, full of misunderstanding, misuse and ignorance. But times have changed, since the last five years JavaScript has been gaining more and more attention. With more attention, more developers are actually using JavaScript, using it for many different purposes and enjoying its beauty. Classical "Ugly Duckling" story, if you ask me.
In the following article, we will discover 10 use cases for JavaScript that are different from the common "in browser" ones, you're used to.
01. It's time for a hangout
Do you remember the 80s vision of Facetime-like video communication?
It only took 20 years before this has gone mainstream due to nearly everywhere available broadband internet and the heavy use of a little software called Skype.
With the capabilities of Adobe's Flash and Google's attempt to build a social network, we already have the capabilities of video communication in our browser. Wouldn't it be cool to have those abilities without using a third-party plug-in such as Flash?
Fortunately, the browser vendors thought the same and implemented the "getUserMedia" API into their software. This was a first step in order to access devices like cameras or microphones directly from your browser.
Using Node.js as a server in the back of such an application, it's amazingly easy to transport the video signal over the air to one or more clients. Unluckily, by the time of writing this, only Chrome and Opera are supporting the API, but others will catch up fast.
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
The cleaner approach for a two way communication is a Chrome only thing at the moment, called WebRTC. Because of WebRTC, clients are enabled to open peer to peer communication channels, directly connecting client with client.
For the sake of fun, check out Sindre Sorhus' Photo Booth implementation done in 121 bytes!
var video = document.getElementsByTagName('video')[0],
navigator.getUserMedia('video', successCallback, errorCallback);
function successCallback(stream) {
video.src = stream;
}
function errorCallback(error) {
console.log(error);
}
02. $('light').fadeIn();
The Arduino microcontroller platform is a grade A example for an "out of the box" JavaScript use case. For those of you, who are not familiar with the Arduino platform, here's a super famous quote from its website:
"Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments."
The Arduino itself only supports code written in C, which is still no big deal. With a few lines of C (besides that others have done this work for you), the Arduino can receive commands through its USB port via the serial port protocol.
But how can you access the serial port via JavaScript? Clearly not from the browser.
Node.js to the rescue!
Due to the efforts of community advocate Chris Williams, we have a Node serial port library, where we can send data over the old SP protocol. This was the initial breakthrough, based on the library other people came up with a more abstract approach for Arduino's capabilities. For instance the node-arduino and duino libraries.
The hottest and coolest library around the block for JS driven Arduino programming by now is jonny-five. Check out Bocoup's blog for some hot shit they've done with the Arduino platform and plenty of plug-ins. Also the JSConf video from Nicolai Onken and Jörn Zaefferer might give you a spin of what's possible today with little code.
03. Your hands are made for the browser
Minority Report's future vision (the one where they control computers with their hands, not the ugly cars) comes closer every day. A huge step in this direction was Microsoft's controller less playing attempt, Kinect. Amazing gameplay you might think, but what has this got to do with JavaScript?!
With Microsoft's Kinect SDK release, a bunch of people crossed the bridge of in browser use for the Kinect. First of all the guys of ChildNodes who have built a complete working kinect.js library, that enables the use of Microsoft's Kinect in your browser.
I highly recommend to check out their demos and videos, it's a blast. One major drawback of the kinect.js library, however, is, that there must be a WebSocket server program running in the back of the client (that's actually the Kinect -> C# -> JS glue).
A few students of MIT fame are working on a solution to tear down this wall, called DepthJS,
an in browser plugin which enables the Kinect use for Chrome and Safari, even for sites that aren't optimised for a Kinect based use in any form. DepthJS currently is in an early development stage, but definitely worth to keep track of.
04. 3D games controlled with your gamepad
Have you ever tried to play a non-Flash browser game nowadays? The graphic capabilities are amazing, especially when you see game clones like Quake.
But when playing this stuff you're always tied to your keyboard and the (mostly) clunky mouse. This is a major disadvantage, in particular for action games, it really holds them back from the browser.
Wouldn't it be cool if you just could plug your Xbox controller into your PC and start playing your favourite browser game? This is not a future vision anymore, say hello to the Gamepad API!
If you are having a gamepad around your desk, plug it in right now and enjoy some games, that already are using the Gamepad API. Programming the input controls also is a piece of cake, check out this code snippet or even better, run it yourself:
<div id="gamepads"></div>
<script>
function gamepadConnected(event) {
var gamepads = document.getElementById("gamepads"),
gamepadId = event.gamepad.id;
gamepads.innerHTML += " Gamepad Connected (id=" + gamepadId + ")";
}
window.addEventListener("MozGamepadConnected", gamepadConnected, false);
</script>
If you would like to know more about browsers' 3D capabilities check out Three.js and Jens Arps' open source 3D simulator engine Ascent built on top of it. Mark Hammil watch out, we might need you for another Wing Commander sequel!
05. Running Flash on your iPad
As an open standards lover and Apple fanboy I have to admit that I'd really like to thank Apple for not putting Flash on the iPad and iPod, this really started a movement of embracing open technologies like HTML5, CSS3 and JavaScript.
As an agency employee, I have to say that this is a really bad situation for our customers.
Most of them have to pay twice for a simple ad or campaign that they're launching to have interactive content running in old IE7 or IE8 via Flash and on modern browsers as well as iDevices via HTML5.
Polyfilling the old browsers' features has its borders, mostly named performance. So isn't there a capability of running Flash on those Flashless iDevices?
Of course there's one, and of course it's built in JavaScript.
A piece of history: In 2010 Tobias Schneider released a little library called Gordon
which allowed SWF files to run directly in the browser. This worked pretty well for small Flash files like ads that only used functionalities up to Flash version 2, but higher level functionality wasn't included at all.
When Tobias joined the ueberJS company UXEBU, they came up with a new idea.
And so, Bikeshed was born. Bikeshed itself is a kind of JavaScript animation framework, but is also a JavaScript to Flash to everything you want it to be compiler (it's adapter based, so you can write adapters for anything you want, though the standard behaviour is compiling Flash to JavaScript). It's compatible to Flash 10 and ActionScript 3. Take a look at its web page to learn more about its plenty of features besides the compiler.
06. Writing apps for your smartphone
Writing native applications for mobile phone environments is a rocky road. It starts with the decision which platform you want to support. Should your application run on an iPhone and iPad, an Android powered mobile device, Windows Mobile, Blackberry devices, webOS based pla... and so on.
Each of this platforms has its own APIs and mostly uses different programming languages.
If you've survived the browser wars, let me tell you that this is a way harder fight to get in. It's nearly impossible for a developer to build an application for all of these platforms in time and budget.
So what to do? Hire more developers? Charge more for apps? Or find a better approach to make sure your code base runs on every device? As the most of you, I would prefer the last approach.
But in what should these apps be built? What have all of these platforms in common? You might know the answer, it's a web browser and therefore a JavaScript engine.
That's the idea behind Apache Cordova, better known under its former name PhoneGap.
Cordova is a JavaScript framework which abstracts the APIs of each mobile environment and exposes a neat JavaScript API to control all of them. This enables you to maintain a single code base, which you then build and deploy on different mobile devices.
Check out the resources here to find out how to use Cordova to build kick ass mobile apps that you build once and will run everywhere.
07. Running Ruby and Python in your browser
Mozilla, the company behind the famous Firefox browser, employs a lot of geeks, that's for sure. One of 'em is Alon Zakai an engineer at the Mozilla Research Team, that built a freaky tool called Emscripten.
Emscripten lets you take LLVM bitcode – which can be generated from C/C++ based libraries, to JavaScript. It does this by compiling the libraries into bit code and then, taking that bit code and transforming it into JavaScript. Neat, but what can I actually do with this, you might ask yourself?
I have a counter question for you: have you ever heard the phrase "Using CoffeeScript and Prototype is the closest you can get of running Ruby in the browser"? No? Don't worry, because this isn't true anymore.
With Emscripten you can simply take the Ruby sources, transform them into JavaScript and voilà, have the real Ruby running in your browser! But this doesn't apply to Ruby only, Python for instance was also emscriptened.
Or check out the in browser h.264 decoder Broadway. That is actually an emscriptened C++ library!
Go to repl.it to see a few programming languages (including Ruby and Python) running in your browser!
08. Writing OS independent desktop programs
We talked about targeting multiple mobile platforms with the help of Apache Cordova before. Unsurprisingly, JavaScript can not only be used to target mobile platforms, our old friend the desktop computer can be tackled, too.
The first solutions came from the guys of Appcelerator with the Titanium Desktop Suite and from Adobe the widely used Air platform.
But as the open source lovers that we all are, a more open and Node.js based technology is what we are looking for. Meet app.js! app.js is an open webtechnology and Node.js based desktop program builder, that allows us to write real desktop programs with file system access, window controls and more. We can rely on the stable cross platform APIs of Node and build our softwares UI with HTML and CSS. Just like the most hot new stuff on this list here.
app.js is a pretty young project and therefore only supports Windows and Linux by now, but according to the mailing list, Mac support is on its way.
09. Running a webserver
Nowadays, you don't shock anybody when you tell 'em that your website is being served by a JavaScript based webserver. If you think back two or three years ago, and told web developers exactly the same, they'd probably have laughed at you or even worse.
But with the incredible success of Node.js this is luckily far away from now. Not only does it not surprise people anymore, due to its asynchronous nature Node.js is a wunderkind in performance, especially when it comes down to facing the problem of a lot of parallel connections. Not only its performance is a blast, the truly simple API attracts a lot of developers, also. Let's check out the "Hello World" example from the Node world, it's not only a print "Hello World" on the screen example, it's a http webserver!
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
If you're not blown away by this simplicity, well, I can't help you either.
One of the best parts of Node popularity (or hype) is, that big companies like Microsoft are actually supporting it, ie in their Azure Cloud Services!
10. Webscraping and screenshotting
So, last but not least, let's take a look at a project that I personally love for letting me run my QUnit tests headless on the command line. PhantomJS is a headless WebKit based browser with a neat JavaScript (or CoffeScript) based API.
But testing your JavaScript and DOM isn't the only use case for Phantom. What really fascinates me are its capabilities to scrape websites and to let you take screenshots of it!
Yeah, you're reading right, with Phantom you can output webpages in different graphical formats and, of course, it's as easy as stealing sweets from a baby.
Let's take a look at a script that exactly does this:
var page = new WebPage();
page.open('http://google.com', function (status) {
page.render('google.png');
phantom.exit();
});
That's all you need to make a screenshot and because it is JavaScript based, you could also use jQuery and manipulate the page contents before screenshotting it!
Wait! There's more...
So, I hope you're as amazed as I was, when I discovered every one of these tools. This article just scratched the surface of what is possible with JavaScript nowadays. There's so much more like IDEs entirely written in JS Cloud9 or high security stuff done with it (Your Credit Card was made with JavaScript).
I hope you feel inspired, take some time and play around with some of the projects mentioned here, or even better take some of these tools and build new stuff around them. Most of this here is open source and there are developers out there, looking for you to help them improve their work, even if it's only by using the tools, discovering bugs and reporting them.
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.