javascript

jQuery GooglePlus Widget

I have just been toying around a few minutes with the google+ api.

The result is a small jQuery plugin that can display and update a users activity stream.

Setting up the plugin is really simple – just include it using

<script src="https://raw.github.com/wbg/jQuery-GooglePlus-Widget/master/js/jquery.googleplus.widget.min.js"></script>

And start it using

$(function() {
  	       $('#target').googleplusWidget({api_key:'API KEY',user_id:'USER ID'}).trigger('start_gplus');
});

You can register an API key using the google api console: https://code.google.com/apis/console/

Get it on github


Javascript Video Pixel Manipulation

A simple implementation of the good old water demoscene effect with a little twist. It works on the pixel data of a video playing in realtime. Check out the demo here. More infos soon. Be sure to use a recent version of Google Chrome or Apple Safari.


Fun with video and CSS3

To get rid of the nasty sparetime i created a little fun experiment that uses HTML5 <video> + <canvas> and some CSS3 transforms to perform some interesting transition / slicing effects on video elements. It only works in webkit based Browsers i.e. Apple Safari and Google Chrome. Below is a link to the demo and a really short howto explaining the technique behind it.

Watch the demo first.

Howto

The code is pretty simple and straightforward. In essence you need a video tag to play the video, some canvas elements that act as your video slices and finally some css transforms to animate the canvas elements.

Video

HTML5 <video> makes playing videos (nearly) as simple as displaying an image on your website. The only thing slightly problematic is the codec support in different browsers. To satisfy all class A browsers, you would need at least three videos with different encodings (ogg, webm, h.264), but as these demo only covers webkit, at least ogg is not needed.

To embed the video you can use something like this:

<video id="video" loop autoplay controls style="display:none">
<source src="trailer_480p.m4v" type="video/mp4">
<source src="trailer_480p.webm" type="video/webm">
</video>

This defines a video element with some additional parameters: The source tags define the video files in different encodings, the loop, autoplay and controls attributes should be self explanatory.

To encode videos in h.264 i simply use handbrake, Miro Video Converter does a good job at creating WebM videos. Both tools are available for free.

Javascript

The javascript code is not that complicated either. In essence you just need to update some canvas elements with the video content periodically. This is simply done by rendering the video to the canvas element. The code is really straightforward:

var canvas1 = document.getElementById('canvas1')[0];
var ctx1 = canvas1.getContext('2d');
// ... repeat for remaining canvas elements
var video = document.getElementsByTagName('video')[0];
video.addEventListener('play', function() {
	setInterval(function() {
		ctx1.drawImage(video, 0,0, 854, 480);
		// ... repeat for remaining canvas elements

}, 33); }, false);

A possible speedup could be achived by rendering the video to a single large hidden canvas element an render this to the visible elements. Still I did not bother to test the speed improvements for this small example.

CSS3

As slices of the video are rendered to different canvas by now, you can use standard css3 transformation effect on them. To get at least minimal speed on mobile browsers, you should always use 3d transforms instead for their 2d counterparts as those are hardware accelerated e.g. translate3d(10px,10px,0px) instead of translate(10px, 10px). More details on CSS3 transforms can be found here.

The Movie

Last but not least: the excelent open source movie used for this demo is of course Big Buck Bunny (c) copyright 2008, Blender Foundation. A truly amazing achievement of the open source community.


dada-dada.tv launch

In a collaborative effort EN GARDE and TAO Software lauched dada-dada.tv today. Beautiful design meets some nice Javascript/HTML5 enhacements.


ios 4.2 update with important mobile safari features

Apple released the new ios version 4.2 for iphone, ipod touch and ipad yesterday.

This update sports lots of new features and security fixes. Among others the mobile safari (webkit) feature set was seriously improved. It now features

  • The new Device Orientation API (Accelerometer access without phonegap)
  • Better HTML5 Form Support
  • New HTML5 events like onhashchange
  • Better SVG Support
  • ImageData Support for the Canvas API
  • The all WebSockets API – this one is huge
  • Partial support for XMLHttpRequest Level 2
  • And last but not least support for typed arrays is on the way

Looks like this update is really important for anyone developing webapps for the iphone/ipad. The only thing missing are detailed informations about tweaks to the hardware acceleration.

Now if only A1 would sell the iPhone 4 already. Bugs me that i can not test stuff on the retina display. Latest rumors are 29. November.


status.net extension for the LiveTwitter jQuery plugin

There are a few good reasons to use the twitter alternative status.net / identi.ca (formerly laconica). First of all it is an open source plattform. Second one of the main goals of status.net is to let it’s users keep controll of their data. It supports open protocols like XMPP and standards like FOAF to export your data. Copyrighting your posts using creative commons is also integrated. Furthermore you can install your own status.net server.

These arguments convinced me, that using status.net is a good idea. The first thing i missed was a simple widget to display status.net posts on a webpage – unlike twitter, the available javascript widgets are quite few and not very elegant.

Luckily status.net implements a nearly twitter compatible api. So it should be rather easy to use existing twitter widgets with it. My favourite one is jQuery LiveTwitter, as it is clean, simple and robust. It took just a few minutes to fork it on github, add a few lines of code + settings and voilà it displayed identi.ca status messages.

My fork is of course available on github. The only difference to using the original LiveTwitter is an additional option service that expects a status.net hostname. If you leave this option blank, Twitter is used as usual. A quick example could look like this:

<script type="text/javascript" charset="utf-8"
src="jquery.livetwitter/jquery.livetwitter.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
    $('#target').liveTwitter('test', {service:'identi.ca'});
});
</script>

That would search for the Term test on identi.ca. Any other hostname like youraccount.status.net work as well.

The only thing missing in this extension is a way to use twitter style list queries on status.net. This will be emulated in another commit using status.net’s groups feature.

Update: this extension is now included in the original jQuery live-twitter plugin.


Javascript Graphics Resources – SVG, Canvas, Infovis

Lazy weekend collection – some useful visualization libraries for your Javascript Applications.

jQuery SVG is a nice structured plugin that allows you to interact with SVG-Canvas Elements. It also features extensions for graphing and plotting.

Raphaël on the other hand is a simply kept library to handle your Vector-Graphics needs on the web. Especially interesting is the support of SVG as well as VML. The last one providing a decent fallback for some well known not-so-good browsers.

Interesting new development: mozilla added mozRequestAnimationFrame for better animation timing with html5 / css3 browsers. Looks very interesting, the only drawback is, that it is an experiment and not guaranteed to stay.

And finally some really awesome stuff: JavaScript InfoVis Toolkit is a stunning tool for creating infovisualizations on the web. Developed since 2008 it features a boatload of visualization techniques and what is especially impressive: you can interact with your graphs and everything is smoothly animated.


Accurate javascript geolocation with current (mobile) browsers

With GPS chipsets x as well as modern webbrowsers present in most mobile devices (iPhone and Android Phones, Tablets and even Notebooks) these days, it is surely time to start using geolocation with your webservices.

This is actually quite simple, as most current browsers (this as always excludes internet explorer) implement the W3C Geolocation API Specification. As seen in many tutorials, you simple check if the navigator.geolocation object exists, call navigator.geolocation.getCurrentPosition(my_callback) and get the current location of your user.

Nice and easy, but there is one little Problem: on most devices, this can lead to very inaccurate results. For example the iPhone 3G often returns positions with 500m accuracy, even if you pass the enableHighAccuracy:true. So watching the current position until it’s accuracy stabilizes is inevitable if you want to serve your user with pleasing results. Also this enables you to add some nice ‘wait for it’ animation that shows the current degree of accuracy – as for example seen in the iPhone Maps Application.

Luckily the Geolocation API also specifies the watchLocation function. This one can be called like that: var watch_id = navigator.geolocation.watchPosition(your_callback). This way your callback gets called everytime the users position or the accuracy of the current position changes. Under good conditions it just takes a few seconds to reach good enough accuracy for your application. As soon as your callback gets a position with good enough accuracy, you should call navigator.geolocation.clearWatch(watch_id) to disable the GPS again. This is especially important on mobile devices where an always on GPS can drain the battery quite fast.

To ease the usage of the geolocation api, i wrote a simple javascript that tries to get the current users location for a specific accuracy threshold. It is as always available on github.

Using it is really easy. Simply call simple_locator with your callbacks and you are done. Check out this quick example:


  var locator_update = function(coords, location_name) {
    var output = document.getElementById('output');
    output.innerHTML = 'lat: ' + coords.latitude +
                                      '; lng: ' + coords.longitude +
                                      '; acc: ' + coords.accuracy +
                                     '' + location_name;
  };
  simple_locator({
    threshold:50,
    running_callback : locator_update,
    finished_callback : locator_update,
  });

As an additional tool i also added reverse geocoding via google maps api v3. Just include the google maps api, set the google_geolocation:true option and the second parameter of your callback will contain the address of the current location. An example can be found in the simple_locator.html file on github.


Javascript libraries – this time nodejs and some extensions

node.js is a high performance, strictly non-blocking I/O server based on googles V8 javascript engine. As HTTP is a first-class protocoll in node, it seems to be very suitable for specific tasks like streaming content over HTTP or high-performance realtime web-applications.

A really nice and clean sinatra-style web application framework for node.js is expressjs. It seems to be a good choice for lightweight web-applications.

Josi also looks like a very usable MVC framework for node and the broke framework is something to look out for as it tries to reimplement the awesome django in javascript (they are looking for helping developers btw.).

Some database drivers/connectors for node.js:

And finally there is a nice article on howtonode.org combining node.js, expressjs and mongodb to build a simple blog engine. Great introduction!


js1k.com

js1k.com is a competition worth checking out. In the spirit of the demo-scene the goal is to create something visually appealing in not more than 1 kilobyte – 1024 bytes – of javascript. No external libraries allowed. All demos work in firefox, opera and webkit browsers.

There are some really cool and inspired entries – be sure to check out the demos. My personal favourite is the javascript theremine.

It’s the taking part that counts so we also quickly put together a small demo.


jQuery plugin: stop cluttering your animation queue with hoverFlow

A typical Problem with jQuery hover animations is, that they build up the animation queue if the mouse is moved before the animation finished. There are quite a few solutions.

First you can use the excellent hoverIntent plugin and set it’s threshold to be above or equal to the animations duration. Another solution is to use jQuery’s stop() function and reset the elements style. Both of these tend to result in rather unnatural behaviors.

A nicer way to reset animations is implemented in the hoverFlow Plugin, that smoothly resets your animations and prevents the buildup of the animation queue. Thanks to Jürgen Genser for sharing it with me.

Implementing it is really straighforward – you simply replace jQuery’s animate() with hoverFlow(). See a quick example below:


Mobile Safari Memory Usage and Images

Mobile Safari is known to quite often crash / terminate silently when loading certain Webpages. Since iOS 4, this happens frequently on older devices like the iPhone 3GS, but sometimes it also happens on newer Phones and the iPad.

The crashes are caused by mobile safari using up all available memory on the device, and as iOS 4 needs more memory for itself, it worsens the situation.

It is quite well known, that mobile safari does not like images that much. So the obvious solution is quite simple: reduce the amount of images on your page. This should be a standard procedure during the development of a useable mobile design anyway, but as Thomas Fuchs pointed out, advanced tricks like replacing gradient images with custom canvas elements can be beneficial too.

This solution is not possible for things like galleries or news sites with large images. In these cases ajax and dynamic loading of image content seems to be the best solution. In essence you load images as they start to move into the viewport and remove them as soon as they leave it – i.e. the user scrolls away. The simple way would be to just remove the image from the dom like in jquery:

$('.my-image').remove()

In our tests this however did not solve the problem, as constant loading and removing of images sooner or later overloaded the little mobile browser and lead to a crash. Still after a little bit of work on our side, we found a solution that seems to prevent memory growth quite effectively. The general idea is to reuse javascript Image objects to load inline image data – some sample code below:

This leads to a bit more work when implementing the frontend, but can quite effectively reduce memory usage and increase stability on mobile safari. We did not test this solutio on devices other than iPhone and iPad, but as mobile safari is webkit based, this solution should also improve pages on android devices. Though these are frequently equipped with much more memory anyway.

And last but not least: try to restrict your use of google web fonts or typekit fonts to a minimum, as loading more than one font weight / loading more than one font seems to crash mobile safari – more details on these problems can be found  on google code as well as the typekit blog.


Updated Javascript Frameworks

DoJo Toolkit: New Version 1.5 sporting new Features and improved Performance all over the Place

And the guys behind the marvelous Sprout Core Application Framework released Sprot Core Touch – another native-application-lookalike library for touch based devices like iphone/ipad and androids. As with Sprout Core itself the performance of Sprout Core touch is stunning.

And last but not least YUI team released a preview of their 3.2.0 version, also sporting various enhancements for touch based devices.