Logo
 

Hey, how are you?

What's New?

October 26, 2012 - Cross domain javascript
jQuery postMessage

If you're in my line of work where you have third parties or vendors that implement specific parts of code on specific domains in web applications (Mashups), you know that communicating through the *CLIENT* side can be a very frustrating and limiting possibility, especially when you want everything to appear seamlessly as one.

Every browser and version have very specific ways of handling client side code, namely javascript. Cross-domain javascript has been a bane of mine for a very long time, having to rethink about projects and their specific implementation, with the usual resort of having it handled on the server side.
Recently, I discovered a very effective and backwards compatible plugin for jQuery called jQuery postMessage by Ben Alman. No longer is it impossible for the scenario where a third party iframe on a different domain is not able to communicate back to it's parent. With this plugin, all that is needed is including the required sources and literally a few lines of code. Nice!
Modern browsers now support cross-window/cross-domain/cross-origin messaging
through window.postMessage.
postmessage is a simple wrapper for window.postMessage and the window message event, for those who wish to use this feature in a more jQuery-like way. postmessage falls back to window location hash polling for browsers that do not support window.postMessage (i.e., IE7).
The heart of the code is two methods, one in the parent and one in the child(iframe). The parent in this case will be the receiver of messages from the child, in which the method is named so rightly:

$.receiveMessage(
function(e){
alert(e.data);
//handle the string data that will be received of Hello World!
},
'http://urlToDomainOfChild.html'
);

Simple? The child implements this little block of code:

$.postMessage(
'Hello World!',
'http://urlToDomainOfParent.html',
parent
);

Sooo simple. It was a godsend and has forced me to rewrite a lot of the code for functionality that would otherwise be relegated elsewhere, and is opening up new ideas on it's use.
I've tested it in IE7, IE8, and IE9 and all works beautifully.
February 21, 2012 - Javascript Multithreading
Javascript Multithreading

One of the biggest downsides when working with ActionScript/FLEX/Javascript projects in the past was the inability to run specific, heavy processes in the application without those processes affecting the performance of the application.
For example, having a button that upon being clicked, would initiate some sort of process and have some sort of UI event such as an animation. What would happen most of the time if that animation was tied to a heavy processing method was it would either freeze the application, or cause a less than desirable transition of that animation and whatever other processes that was occurring in the application at the time the button was clicked. Unfortunately all of that can't be simultaneous due to limitations in browsers' Javascript runtime and the Flash AVM. Script execution happens within a single thread.
Sure, there are API within Actionscript and Javascript such as XMLHttpRequest(), AsyncToken() and even setTimeOut() and setInterval(). Even though these features run asynchronously, asynchronous events are processed after the current executing script has yielded.
Multi-threading is still not supported in ActionScript, and having all processes executed in a single thread poses questionable aspects on the performance of Flash applications.
The same holds true for Javascript, until now, with the HTML5 spec on Web Workers. Web Workers are basically a API specification that lets you create background Javascript threads to process CPU intensive tasks. Normally in browsers a single thread is created to handle all the Javascript code. So whatever Javascript code is run in the browser is executed in that single thread; whether you are doing some calculation or updating page elements. The downside of this is that some CPU intensive piece of Javascript can render the page unresponsive or slow it to a crawl.
To instantiate a Web Worker, one only has to declare it like so:

var worker = new Worker('workerTask.js');

In the constructor of the Worker object is passed the location of the external Javascript file that will execute the processing task for you. This can be anything, such as iterating through a big loop for example:

for (var i = 0; i <= 10000000000; i++){
var j = i;
}
self.postMessage('WORKER COMPLETED PROCESS WITH BIG LOOP: ' + j);

So in this example, the worker is iterating through a loop of 10 billion. Executing this script on a main thread would render your machine useless for about a minute as it loops through to 10 billion. But with Workers, you run this task in a seperate thread and leave the main thread to handle it's own tasks - meaning that the main thread will not freeze until this worker task is complete.
To start the worker, the API specifies to call the postMessage method. So in this example, a button starts the process to initiate the 'big' process like so:

var worker = new Worker('sometask.js');
someButton.addEventListener('click',startProcess,false);
function startProcess(){
worker.postMessage({'cmd':'start'});
}

This example passes a JSON object to the worker to process a command of 'start'. The worker Javascript then looks like so:

self.addEventListener('message',onMessage,false);
var inter = 0;
function onMessage(e){
var data = e.data;
switch (data.cmd){
case 'start':
for (var i = 0; i <= 10000000000; i++){
var j = i;
}
self.postMessage('WORKER COMPLETED PROCESS WITH BIG LOOP: ' + j);
break;
case 'stop':
self.postMessage('WORKER STOPPED: ' + data.msg);
self.close();
break;
}
}

The worker listens for the message event in which case it posts the message back when it has completed its task. Then, in the main thread, we listen for the response from the worker like so:

var _response = document.getElementById('response');
function handleMessage(e){
_response.value = e.data;
}
<textarea id='response'></textarea>

And that's all there is to it. You can view this example here: Javascript Multithreading. Please remember as with all HTML5 specifications, different browsers may behave and or support Web Workers differently. Currently, Web Workers are supported in Chrome, Firefox, Safari and Opera.
Internet Explorer is the kid eating glue in corner...
February 17, 2012 - HTML5 WebStorage
HTML5 WebStorage

WebStorage is another new feature of HTML5 that replaces the old cookie model that's been used in browsers from the very beginning. WebStorage allows web applications to store data locally within the user's browser.
Earlier, this was done with cookies. However, WebStorage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
The localStorage ObjectThe localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year. For Example:

localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;

Create a localStorage key/value pair with key="lastname" and value="Smith",
Retrieve the value of the "lastname" key and insert it into the element with id="result."
Key/value pairs are always stored as strings. Remember to convert them to another format when needed.
The sessionStorage ObjectThe sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:

if (sessionStorage.clickcount)
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";

Since this is a new HTML5 spec, different browsers support and behave differently to this object, with IE having the lowest amount of support and Chrome having the highest. I recommend using Chrome and Safari for this example. This will not work with IE, Firefox or Opera.
Give it a try! HTML5 WebStorage. It's also important to note that each browser will hold a seperate database for the data you have created, and it will not work cross-browser. WebStorage can only read data on the same domain. WebStorage is also not as persistent as say, SharedObjects in ActionScript. Deleting one's cache and cookies will delete the WebStorage database per browser.
February 16, 2012 - Video in a video via HTML5
Video in a video HTML5

Been playing around with more of HTML5 <video> and created this cool video in video test. It basically replicates video playing in a thumbnail of a main video, and when that thumbnail is clicked will switch over to the thumbnail video and maximize.
The example uses some jQuery and CSS3 for the transitioning from the minimized video to the large one. The most important part of the javascript that makes the two videos look like they're embedded within another is in this snippet. You can do a whole punch of other things such as preload the video, use the video events such as 'canplaythrough' or 'canplay' which I have before you can even access the videos to make the user experience a little bit more friendly.
I have registered the 'canplay' event for the videos, so before you can interact with the interface, I have placed a mask on top of the application with a 'Loading videos' message and I wait for each video to fire their events before interaction is possible. I chose to do this because I detest my own experiences with web video when buffering is not ready and I try to play the video. So in this case, I at least wait until part of the video is able to be played.
Your video can be quite large depending, so it is also a wise choice to use the 'progress' event when buffering HTML5 videos. Quite similar to the way the progress events are handled if you've done it enough times with ActionScript.

var minimized = document.querySelector('.view1 #clip2, .view2 #clip1');
var full = document.querySelector('.view2 #clip2, .view1 #clip1');
var wrap = document.getElementById('video-wrap');
wrap.className = wrap.className.replace('view1','save1') .replace('view2','view1').replace('save1','view2') .replace('paused','playing');

The basic jist of this is swapping classes for the defined elements and using CSS3 transitions such as -webkit-transition to define the animations between switching between the videos.
Not overly complicated, and creates a nice effect for the end user if contextualized properly.
Give it a try! Have a look at my dog Sabicas and my girlfriend's dog Vixen when they walk in dog boots. Video in a video - HTML5February 14, 2012 - HTML5 Drag and Drop Photo Collage maker
HTML5 Drag and Drop

Building on more capabilities of HTML5 and the Canvas, I have created another version of the canvas photo collage maker. This time, I have incorporated a drag and drop feature. With this addition, the user can now drag the image files from the desktop or explorer/finder window to the designated 'drop zone' specified in the example. Much easier from a user's perspective, and I have even styled the drop zone area to determine whether or not you have tried to drop an image file.
The heart of this new functionality is the DataTransfer object. The dataTransfer property is where all the drag and drop magic happens. It holds the piece of data sent in a drag action. dataTransfer is set in the dragstart event and read/handled in the drop event.
In this example we create a <div> element in which we assign it an id that specifies it as the 'drop zone' for the image files to be transferred to.

<div id='drop_zone'><span id='dropMess'>Drag and drop images here</span><br/><output id='list'></output></div>

We create some default messaging as well as an <output> tag to hold the display of currently dropped images in the application. Once we have defined the elements we can start attaching the listeners for the drag events and methods to handle them.

<script>
dropZone = document.getElementById('drop_zone');
dropMess = document.getElementById('dropMess');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragOut, false);
dropZone.addEventListener('drop', handleFileDropSelect, false);
function handleDragOver(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}
function handleDragOut(e){
dropZone.style.background = 'none';
}
function handleFileDropSelect(e) {
//make sure these are called, otherwise Firefox will redirect to the image file dropped
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
//give some sort of notification that the file dropped is not an image
continue;
}
</script>

And that's the meat of the HTML5 DataTransfer object! It's important to note the support for this API. I've tested it in Chrome and Firefox which work beautifully. Opera and IE have no current support. Safari, I did not bother testing considering the FileTransfer object would've stopped me even if DataTransfer was supported. So you're best bets for testing this example is Chrome and Firefox.
Give my example a whirl for yourself. HTML5 Drag and Drop Photo CollageFebruary 13, 2012 - Canvas Photo Collage maker in HTML5
HTML5 Canvas Collage Maker

Last week I had an interesting experiment using some of YAHOO's developer APIs called the YUI library. With that library came a very cool example of using the YUI framework, along with the HTML5 Canvas element and create a photo collage maker for your desktop wallpaper or otherwise.
The previous example had static images, in that the images were a part of the Canvas and manipulation and exporting were limited to only those images. I have created a newer version that allows the user to upload any image from their machine and create/manipulate their own images.
The main change is the addition of the FileReader object. The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained in one of two ways: from a FileList object returned as a result of a user selecting files using the <input> element, or from a drag and drop operation's DataTransfer object.
The FileReader object is not supported in Safari. So it's important to note that this version can only be viewed in Chrome, Firefox or Opera. I won't even go into IE as it doesn't support a lot more. I really don't know how IE manages to hang around or fall on deaf ears for that matter, while it gets left in the smoke of standards that the rest of the browsers have implemented.
With this main feature implemented, adding images to YUI's CanvasElement becomes a breeze. I must admit I enjoy this simple application. I have already utilized it for creating my desktop background on my home machine.
It's probably best to upload smaller file sized images, and less images at once. I haven't really thoroughly tested this, considering it was more of an example, but it can handle a fair amount of images at varying file sizes.
I tried importing a directory of images straight from my DSLR with the average image file size about 5 meg or so, and although it took a couple seconds to add to the canvas, once there the performance was decent with manipulating them. You can add an unlimited amount of images, but really you will be limited to the real estate on your monitor, in which you won't be able to see all the images in excess.
The image exported will be the size that your browser window is currently in, so it's best to maximize the window to get the largest image size possible. In terms of the two formats, JPEG or PNG, it's probably better to go with JPG, since PNG will be quite a heavy file size for an image that will be comparable quality wise to JPG.
So give it a go and create some nice desktop wallpapers! HTML5 Canvas Collage MakerFebruray 7, 2012 - Canvas Collage to Image export
Canvas to Image

Been playing around with some external HTML5 APIs and found one from Yahoo(YUI).
The YUI Library is an open source Javascript and CSS framework for building richly interactive web applications. YUI is a proven, scalable, fast and robust framework designed to give front-end developers a very scalable API to build rich internet applications.
This example uses a canvas element from the YUI API to create a screenshot of assembled images into an exported JPG or PNG image. The application allows the user to drag, resize and change the orientation of the images provided in the canvas. You can drag corners(as well) as show them and drag, resize and rotate the images in any orientation desired.
Once the positioning and sizing of the images are set you have two image choices in which to export the collage. The exported image is sized according to the user's browser window size at the time of clicking of the export buttons, so this becomes a really cool application to create some custom desktop backgrounds.
The API for this application consists of 3 source files from the YUI library, source them appropriately on your page. The application is then instantiated by creating a var which is then cast as a prototype class. Then that class is instantiated through a YUI API event which listens to the load event of the window.
The DOM is instantiated with a <canvas> element and <img> tags with ids that are added to the canvas element via array of the YUI API through the YUI.addImage method.
Input radio types and buttons are assigned ids which the YUI API are bound to events and methods to execute functionality such image exporting and border toggling.
Very cool, simple application that showcases some of the cool functionality that the HTML5 <canvas> element can provide, as well as some of the great support out there in terms of javascript frameworks developed to support HTML5 in its infancy.
Give it a try - Canvas Collage to Image export. Please note that most of the tests I do in HTML5 or with some new framework is not likely to be fully functional or functional at all if viewed in IE. Please use Chrome, Firefox, Safari or Opera in that order.
Februray 3, 2012 - Object Oriented Javascript
OOP Javascript

So recently I was asked a question at work about javascript and how it's syntax is relatable to OOP. This is coming from developers that have a background in Actionscript, Java and C++.
Although generally javascript is a very literal language, it is good to be able to implement some sort of OOP principles such as encapsulation for example to your javascript coding. One good way of doing this is through this basic example that uses an example of creating a sword object. In this case we want to create a sword class in which we instantiate a new instance of a sword in our html document.
In this example, we will pass in 3 arguments to describe our sword, its type, name and region. I am using an example of a sword because I've always been interested in traditional Filipino weapons, and I recently found a good site that sells some pretty cool authentic swords (Ordering one soon!).
Ok, back to this example. The first thing we want to do is to create our html document and set up the necessary elements before we create our class.

<!DOCTYPE html>
<html lang='en'>
<head>
<title>Lester Flor - lesterflor.com - Javascript and OOP</title>
<meta charset='utf-8'>
<script>
window.addEventListener('load',init,false);
function init(){
}
</script>
</head>
<body>
</body>
</html>

So this is the basic structure that is super easy and should be simple enough for you to always remember to do when developing with javascript. In my personal preference, I like to create an event listener in javascript that listens for the load event. This is a matter of preference as some like to instantiate their init function through a DOM element. It's up to you. So once, you have that ready and going, we can start on our Sword class which will simply print out a statement in the browsers console. The class looks like this:

(function(window){
function Sword(type, name, region){
var _type = type;
var _name = name;
var _region = region;
this.getType = function(){ return _type;};
this.getName = function(){ return _name;};
this.getRegion = function(){ return _region;};
}
Sword.prototype.identifySword = function(){
console.log(getSwordInfo(this));
};
function getSwordInfo(context){
return "This sword is a " + context.getType() + " sword called a " + context.getName() + " from the " + context.getRegion() + "."
}
window.Sword = Sword;
}(window));

So the most important thing to know about this syntax is the instantiation of this class. To do this, we are creating an anonymous function that we bind to the window that will execute when the window is available. This is defined this way:

(function(window){
//class members and methods
}(window));

This is the basic shell for creating a javascript class. We create an anonymous function that we bind to the window element, and then we execute that once the window is ready.
Now we can create the constructor for this class, we do that through creating the Sword() method. This method has 3 arguments as stated before: we pass the type, name and region of the sword. In this example, we are going to make these members private to this class, so by declaring a variable for each of the passed arguments, we effectively make this private to this class.
Now if we wanted to access these members outside of our constructor, we would have to create a getter method for each of the variables that we want to make accessible outside the constructor. We can make it available through the 'this' keyword (which references the globalilty of this class) and attaching a function that will return our chosen member.
To make a public method to our class, we use the prototype keyword plus the name of the method to this class. In this method we simply print out to the console with a concatenated string of our sword members. We access these members through another method that returns the context of this class - in this case, the 'this' keyword references the global aspect of this class and we call the getter functions for each of the members.
The last and most important thing is to attach the global instance of this class to the window, and we establish that by stating:

window.Sword = Sword;

By doing this, we can now return to our html file and source our class and instantiate a new object based on that class:

<!DOCTYPE html>
<html lang='en'>
<head>
<title>Lester Flor - lesterflor.com - Javascript and OOP</title>
<meta charset='utf-8'>
<script src='JS/Sword.js'></script>
<script>
window.addEventListener('load',init,false);
function init(){
var mySword = new Sword('Moro', 'Barong', 'Philippines');
mySword.identifySword();

}
</script>
</head>
<body>
</body>
</html>

And that's it! If you run this code in the browser and view the console, you should see the message. Very simple and basic example, but goes to show how OOP developers in different OOP languages can implicate the same principles within javascript.
January 30, 2012 - HTML5 Video!
HTML5 Video

So I've been doing some tests using one of HTML5's tags, the <video> tag. In terms of implementation, super easy and painless, as long as you have rendered out to the codecs that the major browsers use (H.264, Ogg, WebM). I even created a Flash fallback should the user end up viewing this on anything below IE9 (IE is the bane of every developer's existence).
Although, implementation was very easy, there are several things that you need to take into account when implementing the HTML5 video tag.
One quick thing to note for Safari - if you do not have Quicktime installed, the HTML <video> tag will not be supported. Funny how Apple bashes Flash, yet won't allow open standards be implemented unless you have *their* plugin.
Make sure that the webserver that you are serving your rendered video files SUPPORT the MIME type that you are trying to serve. In my scenario (IIS7), the webserver did not support OGG, MP4, WebM and even .f4a by default, so the workaround for this (on IIS7) is to modify your web.config to include the mime types for the missing types.
Simple as adding these nodes to your web.config. If you know the mime types already supported on your webserver, chances are you will not experience any errors implementing the code block below. But if you are unsure, and you add an already supported mime type, chances are you will get an internal server error.

<system.webServer>
<staticContent>
<remove fileExtension=".mp4" />
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
<mimeMap fileExtension=".m4v" mimeType="video/m4v" />
<mimeMap fileExtension=".ogg" mimeType="audio/ogg" />
<mimeMap fileExtension=".oga" mimeType="audio/ogg" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<mimeMap fileExtension=".webm" mimeType="video/webm"/>
<mimeMap fileExtension=".f4a" mimeType="audio/mp4"/>
<mimeMap fileExtension=".f4v" mimeType="video/mp4"/>
<mimeMap fileExtension=".f4p" mimeType="video/mp4"/>
<mimeMap fileExtension=".f4b" mimeType="audio/mp4"/>
</staticContent>
</system.webServer>

Take note of the first node, which REMOVES the mime type of .mp4. I had to do this because of an issue of my webserver causing an internal error when trying to add an already supported mime type. My webserver already supported the .mp4 codec, but the default type was set to audio as opposed to video. So, removing then adding this mime-type fixes that problem.
Another issue is how each user agent renders the tag. No big deal really, but if you want a consistent UI for the video controls, it's best to implement some sort of third party javascript library to make the controls uniform in each browser. But, if you're like me, I could care less, as long as the controls are there for the end-user to manipulate.
Is the HTML5 video tag easier to use than Flash? Well, given HTML5's infancy, no, it was not easier to debug for all browsers, although implementing it was a lot easier than having to do it in Flash. But, my Flash fallback is supported in every browser, even in IE as far back as 6. My UI would be more consistent too. I could also code extra features in my Flash video player that would not be available in a <video> tag.
The nice thing about the <video> tag I did like though was the 'poster' attribute. It allows you to create a nice graphic of your video, like a promotional piece before the user actually plays the video.
So here is an example of HTML5 Video with Flash Fallback. Please also note that this was optimized for mobile viewing, so the layout is designed and based from jQuery mobile.
January 18, 2012 - Flying through the sky with WebGL!
WebGL Clouds

Again, this is not original work, but I can code this from scratch now. I think this is a big part of being a developer, not just being able to copy and paste others code, but be able to implement and understand what it is that you are typing. Fly through the sky!The only part of this example that I did not create from scratch were the vertex and fragment shaders. GLSL is not very intuitive to me at the moment, and it will take some time for me to grasp this C language. But, in the meantime, I will keep on practicing and create more visually appealing experiments like this one.
It's hard to believe the shift I've set myself to since Adobe announced their strategies with Flash over two months ago. I have not fallen on deaf ears and have read the writing on the wall and plunged into the HTML5 bandwagon these past couple of months. I admit, I was hesitant at first, but I am truly enjoying the frameworks and capabilities that HTML5 is maturing into. Given the potential that a lot of the frmaeworks out there can do, and the prominence of more capable browsers (Chrome all the way), it makes even more sense now that Adobe changed their strategies.
I think of the canvas as the html equivalent of a compiled swf, which in principle it is, and perhaps in another world wide web life, it would've been very prudent if Adobe had made the flash plugin a native API of the browser. But obviously, not being open-source, this was far and few from realization, and it took open standards for HTML5 to come into fruition and topple Adobe's dominance.
I only use and work with Flash while at work. Everything you see before you is devoid of it. I have slowly begun to ween off Flash, but not forget nor not continue to progress with it. It is there like my beloved first car that gets me from point A to B. I know it has it quirks and intricacies, but I love driving it no matter what. If it fails to meet my demands for a particular trip, I have my newer car that I know will get me there; reliably and perhaps even more efficiently.
January 16, 2012 - WebGL experiments continue
WebGL Particles

More work with WebGL. I've been hooked on Three.js the last week or so practicing and exercising its API. These examples are certainly not original, but they are exercises in my current knowledge of the API. Check out this particle example, this panoramic viewer or this rendered text scene.
Not particularly useful, but exemplifies some of the simple and cool things that WebGL is bringing to enabled browsers (don't bother viewing this in IE). More to come as I get more proficient in the API.
January 5, 2012 - WebGL is amazing!
WebGL Earth

Check out this 3D rendered interactive earth, rendered with WebGL!WebGL EARTH. This is an amazing example of the capability of HTML5 and how it can leverage the GPU of the end-user's machine. Flash Player 11 may also use WebGL, but this was done completely in javascript and html. The implications of leveraging WebGL for HTML5 pages will be truly an amazing site to see once it matures.
Is Flash dead? I think it will eventually get there. Remember, Flash came into being as a direct result of the browsers of the era not being able to produce the types of effects that it could, but now that HTML5 is slowly being capable of all the things that Flash can do, there would be no reason to support it in the future. I think of Director and Lingo, and how those names are extinct anywhere in technical terms. Exciting times.