Javascript

Articles about JavaScript development and library oriented scripting

JW Player Captions

1

JW Player with captions

JW Player with captions


Captions are a great way to offer multi-lingual media content on your site, but they don't seem easy to add right? Well with the right tools and guidance, it will be very easy:

Setting everything up:

In order for captions to work flawlessly on every major browser, we will be using JW Player version 4.5 (At the time of writing, version 5 and 5.1 don't seem to work well in Internet Explorer)

Once you have that version ready, add the following Flashvars:

 
<param name="flashvars" value="plugins=captions-1&amp;captions=/captions.xml" />
 

Of course you may leave all the other Flashvars you had before (Specially file ;) )

The XML file:

Now that the player is ready, we need to setup the XML file with the captions, so create captions.xml and write the following:

 
<tt xml:lang="en" xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style">
  <body>
<div xml:id="captions">
<p begin="00:00:00" end="00:00:4">Subtitle 1</ p>
<p begin="00:00:4" end="00:00:6">Subtitle 2</ p>
<p begin="00:00:10" end="00:00:12">Subtitle 3</ p>
    </div>
 
  </body>
</tt>
 

As you can see, all we need is to change the Subtitle text, and the begin and end times of each, to set those up.

Generate the XML file with PHP:

If you want to change the language dynamically, you could use PHP to generate the XML using the following headers:

 
header("Content-type: text/xml");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past (no cache)
// And now all the XML data as before
 

If you want to learn how to easily translate your website read my article on that too!

Hope you found this useful!

iPhone orientation change

iPhone web development [Part 2]

0

iPhone orientation changeIn part one of my tutorial on iPhone web development, we talked about the basic stuff (Recognizing iPhones or iPods, setting up special HTML and CSS tags... ) we will now move on to the really clever bit: Orientation detection.

For many sites, we may just have the same thing both on portrait and landscape. But sometimes we will want to use that extra space to display our content differently, and here is how.

Orientation detection with CSS:

We can use some smart CSS3 selectors to ensure that some styles only apply to landscape, or to portrait modes:

/* Portrait */
@media screen and (max-width: 320px){
	h1{ font-size:20px; }
}
/* Landscape */
@media screen and (min-width: 321px){
	h1{ font-size:24px; }
}

Remember that for this to work we must use the viewport meta tag I showed you in my previous tutorial
This media query works (According to Apple's documentation) since iPhone OS 1.0, so there shouldn't be any problem with it, Firefox mobile should also support this, so by using max-device-width and min-width we should be able to develop specific CSS for every device without the need of PHP to include only certain style sheets

Orientation detection with JavaScript:

We can easily detect the device orientation by checking the innerWidth. This method will also work for other PDAs and SmartPhones:

var updateLayout = function() {
  if (window.innerWidth != currentWidth) {
    currentWidth = window.innerWidth;
    var orient = (currentWidth == 320) ? "profile" : "landscape";
    document.body.setAttribute("orient", orient);
    window.scrollTo(0, 1);
  }
};
 
iPhone.DomLoad(updateLayout);
setInterval(updateLayout, 500);

This code will add a new attribute (orient) to the body element, which will be either portrait or landscape. All we have to do now is use CSS to filter out whatever orientation we need:
There is another method, which will work only on the iPhone though:

body[orient="landscape"]{
// CSS code here...
}
// ... or ...
body[orient="portrait"]{
// CSS code here...
}

That JavaScript also hides the toolbar by using the scrollTo() function when the orientation changes,

Next release:

On my next release in this series of iPhone web development tutorials, I will get into the really advanced JavaScript API we have for the iPhone (touch detection, gestures... etc) so stay tuned!


 


Hope you found this useful,
Alex

Play a sound via JavaScript

3

Working in a project recently I found myself in the need of playing a sort of "alert" sound with JavaScript. It turns out there are not so many good options out there. The first thing that came to my mind was to use an embed and the Play and Stop JavaScript controls.

Well that only works in IE and some versions of Netscape so let's just forget about all those tags (embed, bgsound... etc)

So in my search for an easy solution I came across a very neat jQuery plugin that does exactly that job, the jQuery Sound Plugin by Jorn Zaefferer. I have been completely unable to find the plugin Website, so I will post it's code myself here. This plugin is a port from scriptaculous' version by Jules Gravinese.

How to use:

Using this to play a sound couldn't be easier, let's see an example with no parameters except for the file we want to play:

$.sound.play('files/sample.mp3')

This way the mp3 file sample will start playing. If we prefer the sound to start playing stopping the previous one, we can use tracks, this way we can play one sound per track, and every time we set a new sound for a certain track it stops the current sound there:

$.sound.play('files/sample.mp3',{
   track: "track1"
});

Other options are:

// timeout: Specify for how long the sound can play in milliseconds
$.sound.play('files/sample.mp3', {
   timeout: 4000
});

We can store a sound reference in an object so that we can later on stop it:

var sound = $.sound.play('files/sample.mp3');
sound.remove();

And finally we have the option to enable/disable sounds at all:

$.sound.enabled = false;
$.sound.enabled = true

The plugin code:

(function($) {
$.sound = {
	tracks: {},
	enabled: true,
	template: function(src) {
		return '&lt;embed style="height:0" loop="false" src="' + src + '" autostart="true" hidden="true"/&gt;';
	},
	play: function(url, options){
		if (!this.enabled)
			return;
		var settings = $.extend({
			url: url,
			timeout: 2000
		}, options);
		if(settings.track){
			if (this.tracks[settings.track]) {
				var current = this.tracks[settings.track];
				current.Stop &amp;&amp; current.Stop();
				current.remove();
			}
		}
		var element = $.browser.msie
		  	? $('&lt;bgsound/&gt;').attr({
		        src: settings.url,
				loop: 1,
				autostart: true
		      })
		  	: $(this.template(settings.url));
		element.appendTo("body");
		if (settings.track) {
			this.tracks[settings.track] = element;
		}
		setTimeout(function() {
			element.remove();
		}, options.timeout)
		return element;
	}
};
})(jQuery);

I will probably minify this code before I upload it to the production server, so if I don't forget I will also post here the minified version,

Hope you found it useful,
Alex

Perfect jQuery UI rotating tabs

3

Tabs are nice. They create a very elegant interface, and jQuery UI does this marvelously, here we have a little preview of this:

jQuery UI Tabs

jQuery UI Tabs

How to do that?

Include the files

With jQuery and jQuery UI it is dead simple. First, load the JS libraries, I recommend using the hosted files at Google for jQuery:

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"><!--mce:0--></script>
<script src="path/to/jquery UI" type="text/javascript"><!--mce:1--></script>

Remember to include also the CSS files for the UI Theme! Otherwise the tabs won't seem to work!

The HTML for the tabs:

We need a little HTML for our tabs to work:
A wrapper, a few divs with the content, and an unordered list with the tabs:

 
<div id="tabs-rotate">
<ul>
<li><a href="#tab1"><span>Tab 1</span></a></li>
<li><a href="#tab2"><span>Tab 2</span></a></li>
<li><a href="#tab3"><span>Tab 3</span></a></li>
</ul>
<div id="tab1">Tab 1 content</div>
<div id="tab2">Tab 2 content</div>
<div id="tab3">Tab 3 content</div>
</div>
 

The JavaScript:

Now comes the cool part, basically we want to have tabs. But although tabs are nice, people may not realize there is more content, or they might be just too lazy to browse through it, so, why not rotate through the tabs?
jQuery UI does that by itself with a very simple commant, but it is not perfect! So we need to program our tabs to rotate, unless the mouse is over them. This way when a user is looking for a link, the tab will wait!

So here is how this is achieved:

$(document).ready(function(){
	$("#tabs-rotate").tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 3000);
	$('#tabs-rotate').hover(function(){
			$(this).tabs('rotate', 0, false);
		},function(){
			$(this).tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 3000);
		}
	);
});

First we instruct jQuery UI to set up tabs in that div, and to rotate them. Then we use a hover event to control the rotation. On hover no rotation, and on out resume rotation.

Further actions:

Now you may want to stop rotation completely when a tab is clicked. This can be done "easily": First we will add a new handler for the onclick event to the tabs-rotate, which will remove rotation. But we also have to unbind the hover handler we had setup, using the unbind jQuery function:

 
$('#tabs').click(function(){
	$(this).tabs('rotate', 0, false);
	$(this).unbind('hover');
});
 

See it in action

You can see it working on the DJs Music homepage

As with the best stuff, it's terribly simple ;)

Hope you enjoy,
Alex

Event tracking – Google Analytics

0

Hello everyone,
As most people do, I'm sure you use Google Analytics for the stat metrics for some of your sites, so you'll love this new feature:

If you use AJAX in your site, or if you want to track outbound links, or downloads... etc then this is really useful for you.

What is event tracking?

In simple terms, it logs events that happen on your site, for example rate a post (If you have post rating), download a file... or you do some sort of JavaScript processing that you want to measure.

So finally, we can keep track of AJAX interactions with the server, we can log also normal POST requests that do some php processing, like posting a comment, or editing some data in our database.

Using Event Tracking:

This step couldn't be possible easier. First of all make sure you have the new code installed. The new code looks like this:

 
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-3181088-6");
pageTracker._trackPageview();
} catch(err) {}</script>
 

That var pageTracker is what holds the tracking object.

Example:

Imagine we have a site where we feature some sort of mp3 downloads. And we want to track those with Analytics. In the link to the file we would put:

 
<a href="song_file.mp3" title="Download file" onClick="pageTracker._trackEvent('Music', 'Download', 'Song number 4');">Download song</a>
 

As you can see we use the function _trackEvent, from the pageTracker object. This function takes 4 parameters, Category name, action name and a label and value:

 
_trackEvent(category, action, optional_label, optional_value)
 

The category can be used to store different events that are similar, for example in the category music we could use the actions Download, Listen, Rate... And finally the label, that is normally used to refer to which specific object in that category you are referring to, in this case which song.

From the Analytics panel

Wait for a day after you install this to see the data in Google Analytics, and then go to the stats panel, go to the Content tab, then you'll see at the bottom Event Tracking:
I've created a sample profile with some events and I clicked a couple times to show you how it looks like:

Screen capture of the Event Tracking page

Screen capture of the Event Tracking page

Well I hope you found this useful, more information on the Google API

How do you use this?

Have you found any sort of smart uses for this? Please share with us :)

Go to Top