Articles Tagged ‘HTML5’

Going jQuery-free

It’s 2014 and I’m feeling inspired to change my ways. In 2014, I want to go jQuery-free!

Before I get started, I want to clear the air and put in a big fat disclaimer about my opinions on jQuery. Here we go:

jQuery is an excellent library. It is the right answer for the vast majority of websites and developers and is still the best way to do cross-browser JavaScript. What I am against is the notion of that jQuery is the answer to all JavaScript problems.

Lovely, now that’s done, this is why I want to do it. Firstly, as lots of people know, jQuery is quite a weighty library considering what it does. Coming in at 32KB for version 2.x and around 40KB for the IE-compatible (gzipped and minified), it’s a significant chunk of page weight before you’ve even started using it. There are alternatives that support the majority of its functions in the same API, such as Zepto, but even that comes in at around 15KB for the most recent version, and can grow larger. The worst thing for me, is that I don’t use half of the library, all I really do is select elements, use event handlers and delegation, show/hide things and change CSS classes. So, I want a library of utility functions that only does these things.

Word to the wise, this is not a new notion, and follows on very nicely from the work that Remy Sharp has done in this area in his min.js library.

I’m going to write a series of posts as I attempt to separate myself from jQuery, and make my websites leaner and faster. The first of which will be on “what you think you need, and what you actually need” and give you ways to work out if this approach is for you, or if you should be sticking with jQuery. Next, I’ll cover the basics of what a minimalist jQuery library; and finally I’ll cover strategies for dealing with unsupported browsers.

Let me know if there’s anything in particular you want me to cover, and I’ll do my best to go over it for you.

Sketchnotes from LWS Print

September’s London Web Standards Meetup featured UX designers and developers bringing print to life with their tales of making web apps for the FT (Matt Andrews) and an iPad app for The Week (Harry Brignall). Sketchnotes are below.

Sorry it’s not much of a write-up (and a month late) but better late than never.

Interacting with HTML5 Video Players

HTML5 video players are incredibly useful, enabling developers to display video on non-flash devices (I’m looking at you, Apple). It’s really simple to get started with HTML5 video, but when you want to do something more complicated, there’s not much documentation. Thankfully, it’s really quite simple, and this article will show you how to use the HTML5 video JavaScript API to interact with the videos.

Basic video


This is the HTML:

<video id="firstvideo" style="width:100%" controls>
	<source src="http://mirrorblender.top-ix.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_stereo.ogg" >
	<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.mp4" />
</source></video>

This is your standard HTML5 video player, with the standard browser video controls. The video has multiple sources so browsers that only support certain codecs (FireFox and Ogg for example) get the right video.

Let’s say you want the video to start when you click a button. That’s pretty easy, and looks like this:

var firstvideo = document.getElementById('firstvideo');
var playButton = document.getElementById('playfirstVideo');
playButton.addEventListener('click', function(e) { 
	firstvideo.play();
});
//jQuery version
$('#playfirstVideo').on('click', function(e) {
	$('#firstvideo').play();
});


And if you want to pause it:

var stopButton = document.getElementById('stopfirstVideo');
stopButton.addEventListener('click', function(e) { 
	firstvideo.pause();
});
//jQuery version
$('#stopfirstVideo').on('click', function(e) {
	$('#firstvideo').pause();
}


Subscribable events

That’s cool, you can interact with the element through JavaScript. If you’re a fan of the regular video controls, you can still access events fired by the video. The main ones you’ll be interested in are:

  • play – triggered when the video starts playing
  • playing – triggered whilst the video is playing
  • canplay – triggered when the video has been loaded and it can be played
  • pause – triggered when the video is paused
  • ended – triggered when the video has finished

There are lots of others too, a full list can be seen on the W3C demo for HTML5 video. These include events triggered when the video is seeked (skipped forward or backwards in time) and when the time on the video has changed.

It’s simple to hook these up using event listeners to see what’s going on.

Video state:

Try it out using this video, watching the label which says which event was fired last.

	var secondvideo = document.getElementById('secondvideo');
	var statelabel = document.getElementById('videoState');
	secondvideo.addEventListener('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.innerHTML = "Playing";
	});
	// jQuery example
	var statelabel = $('#videoState');
	$('#secondvideo').on('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.html("Playing");
	});

That's the basics, from there you can use the timing event to make a caption system (tag words with data elements and mark them when their time hits in the video).

What about YouTube?

With YouTube and other embedded video players there's no direct access to the video element, which makes interacting with videos in the way shown above very difficult.
Thankfully, the kind folks at Google have thought of this and provided an API to help us through. The whole documentation is on YouTube developers and there's a great player demo, but here's the gist of it.

There's a few gotchas you need to be aware of:

  1. You've got to be using a served web page, local files won't work.
  2. If you're trying to interact more than one YouTube embed on a page, you will need to address each one individually with unique IDs, otherwise the browser won't know which video to interacti with

Got it? Great, let's head into the code.
This first section, is the embed code needed to include the video in the page. This should be standard YouTube embedding stuff.

// The element that the player will be inserted into
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
 
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
  player = new YT.Player('ytplayer', {
    height: '390',
    width: '640',
    videoId: 'g8evyE9TuYk',
    events: {
      'onStateChange': "onytplayerStateChange"
    }
  });
}</iframe></script>

Video state:

That's your YouTube video, now we need to subscribe to the events N.B. there's no need to subscribe to the onYouTubePlayerReady event as you've effectively done this when the API loads

function onytplayerStateChange(e) {
	document.getElementById('ytvideoState').innerHTML = e.data;
}
// jQuery version
function onytplayerStateChange(e) {
	$('#ytvideoState').html(e.data);
}

As the state changes, a different value appears at the bottom. These are: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). From there you can access any function of the YouTube JavaScript API, which mimics the HTML5 spec with a few small changes, such as the play command is playVideo() instead of just play(). Take a look at the documentation for full details about what you can do.

Vimeo too?

Yes, Vimeo can do this too. The API is similar to YouTube, but isn't quite as simple without their Frogaloop library, so have a look at their documentation for the Vimeo JavaScript API.

Summary

So, there you have it, a few bits of code to control different types of HTML5 video that are common on the web. They're really useful for counting the number of views of a video, captions, and generally making videos more interactive. Let me know what uses you come up with for it in the comments.

Sketchnotes from #LWS3D – A 50-line WebGL app

After a summer break, London Web Standards was back with an evening of WebGL with Ilmari Heikkenen from Google and a short demo from Carlos Ulloa of HelloEnjoy. Sketchnotes are below

Carlos Ulloa¬†of Brighton-based HelloEnjoy showed off two demos that he made using Three.js and WebGL. The first was HelloRacer, an interactive look at the 2010 Ferrari F1 car that you can even drive and do handbrake turns in. The second demo got it premiere at LWS, an interactive music video for Ellie Goulding’s “Lights”. Honestly, it was extremely cool, on a Ro.me “3 dreams of black” scale. It’ll appear at the linked URL in the next week or so. There’s a great Q&A session on the London Web Standards blog of the event for more detail on how they did it.

Ilmari Heikkenen showed the gathered crowd how to make a basic WebGL app using Three.js in about 50 lines. He showed off all of the components that you need: a renderer, scene, camera, mesh and lights (and shadows). He went into more depth about vertex shaders and fragment shaders, the GPU effects that make everything look a lot more real.

Ilmari gave examples of a few uses, including games, 3D bar charts and scatter graphs. He then started animating all of these, including a 10,000 point scattergraph that moved in real-time. Finally, he demonstrated a loader for Collada meshes (supported by Maya) and brought in a monster that with a few lines of code started walking around the screen.

Overall, it was a great introduction to the subject, one worth a lot more of your time.

Ilmari’s slides can be found on his blog.