JavaScript

JavaScript Motion Tween - A JavaScript Animation Engine

Tagged:  

Philippe Maegerman has created a JavaScript animation engine for motion tweening similar to what's available in Flash through Actionscript. The library includes the following classes:

  • Tween class
    Tween.js is the base animation class
  • ColorTween class
    ColorTween.js extends the Tween.js class, its purpose is to manage transitions between two colors.
  • OpacityTween class
    OpacityTween.js extends the Tween.js class, its purpose is to manage opacity transitions on visual objects.
  • TextTween class
    TextTween.js extends the Tween.js class, its purpose is to manage text effects.
  • Sequence class
    The sequence.js class allows you to chain Tweens, it means that the Tweens that have been added via the 'addChild()' method will be executed in the sequence they have been added.

His blog includes documentation as well as working examples and sample code displaying the functionality of the library, including the Webber 2.0 Dock Menu Tutorial.

Full source code is also made available for download on the site.

If you're looking for something a little more heavy duty that comes with features other than just animation, then you probably want to check out one of the major JavaScript Frameworks that include animation support:

Please share your comments and experiences with JavaScript animation, these frameworks, or another framework with animation support not listed here.

Spellify 1.0 - An Automatic Text Field Spell Checker

Spellify is a script.aculo.us/prototype based spell checker for form fields that utilizes Google as its spell check engine. Last month, Spellify released version 1.0 - officially taking the application out of beta and bringing it to prime time.

Check out the short video below for a demo:

Homepage: spellify.com
Spell Check for Multiple Lines: spellify.com/extended.html

The Forms Demo:

Requirements
- PHP 4+ with CURL library installed (developed using PHP 4.4.6)
- script.aculo.us 1.8.0 (latest prototype.js, and effects.js required)

Browser Compatibility
IE7, FF2, IE6, Opera 9, Safari 3. May work in other browsers as well.

Visit the download page

Object Oriented JavaScript - Should You Use It? - Part 3

Tagged:  

So we have come to the last of my articles on object oriented JavaScript. You can read the last post by click ing here. This post will be about how JavaScript is proposed to change when (or if as the case may be) ECMAScript 4 (the spec that JavaScript is based on) is supported by the major browsers.

One of the changes that I am most happy about is the new proposed class structure. Yes JavaScript in the near future will be an object oriented language that is more in-line with languages like Java and C#.

Below is how the new structure is proposed.

Classes: A class describes an object by presenting those properties (fields) of the object that are always present (the
fixed properties or fixtures), including variables, constants, and methods16:

class C {
	var val // a variable property
	var large = Infinity // a variable property
	const x = 3.14 // a constant property
	function f(n) { return n+val*2 } // a method property
}

You would create instances of the class using the new method, just as you currently would with the current JavaScript object.

So, the answer to the question of should you use object oriented JavaScript is a resounding, Yes, especially with the direction that it looks like the language is going. For a more information on ECMAScript 4 check out ecmascript.org. To go directly to an overview of ECMAScript 4 script click here.

As always if you have any questions you can leave them in the comments or private message me once you login to this site. Also, if you have anything that you would like to blog about on this site all registered users get their own blog on Ajaxonomy and the most interesting posts will be published to the home page.

Object Oriented JavaScript - Should You Use It? - Part 2

This is the continuation of a post that I wrote yesterday (click here to read the original post). This post will go into much more depth and will be a bit more technical.

Now to begin to answer the question of should you use object oriented JavaScript (don't worry I will touch on the fact that we have all already used JavaScript objects). The first thing that we should understand is how it is used and what are the advantages or disadvantages. If you have been programming in a language like C++ or Java then you are use to a class style of object oriented. JavaScript does not use this structure, instead an object in JavaScript is based on functions and properties.

JavaScript object oriented programming can be noted in different styles.

The first type of notation is to use the new operator along with the Object() method.

person = new Object()
person.name = "John Doe"
person.height = "6Ft"

person.run = function() {
	this.state = "running"
	this.speed = "4ms^-1"
}

In the above code we define an object named person and then add it's own properties. Also the property person.run will execute the function.

The next notation will be familiar if you have ever used JSON. The below notation is referred to as literal notation. This notation simplifies things a bit and this is much better for sending over the web in an Ajax application where such things really matter.

var rectangle = { 
	upperLeft : { x : 2, y : 2 },
	lowerRight : { x : 4, y : 4},
	method1 : function(){alert("Method had been called" + this.upperLeft.x)}
};

The shortcoming with this method is that it does not lend as well to re-usability.

So far you are probably thinking that this is a waste of time and that why would I ever use this, outside of JSON. Well, now we will start to see the power of this coding style which is in re-usability.

The below example will create an object and will set the value of the name property.

function cat(name) {
	this.name = name;
	this.talk = function() {
		alert( this.name + " say meeow!" )
	}
} 

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"

cat2 = new cat("ginger")

The above code shows how you can easily create multiple objects based on the same object. Which brings me to how you have already used object oriented JavaScript. For example the document.getElementById() method is an example of an object that you more than likely have used (don't worry Prototype library lovers, I'll touch on $() in just a moment).

One of the great things with objects is that using prototype (if you have been programming in ActionScript you will be familiar with the below) you can now extend the functionality of an existing object in a new object.

The below code is an example of how to use prototype to extend an object.

cat.prototype.changeName = function(name) {
	this.name = name;
}

firstCat = new cat("pursur")
firstCat.changeName("Bill")
firstCat.talk() //alerts "Bill says meeow!"

Using prototype you can extend existing JavaScript objects, such as the date (I believe that this is how the prototype library creates the $() method which is in essence the document.getElementById() method) object.

The below example shows how to extend array object with the shift and unshift methods that are not available in some browsers.

if(!Array.prototype.shift) { // if this method does not exist..

	Array.prototype.shift = function(){
		firstElement = this[0];
		this.reverse();
		this.length = Math.max(this.length-1,0);
		this.reverse();
		return firstElement;
	}
	
}

if(!Array.prototype.unshift) { // if this method does not exist..
	
	Array.prototype.unshift = function(){
		this.reverse();
		
			for(var i=arguments.length-1;i>=0;i--){
				this[this.length]=arguments[i]
			}
			
		this.reverse();
		return this.length
	}
}

If you have been programming in a language link C++ or Java you are probably very familiar with a class structure. Part of this is the idea of a class and a subclass. While most JavaScript object oriented code will not use the following, below is an example of how you can create classes and subclasses in JavaScript.

function superClass() {
  this.supertest = superTest; //attach method superTest
}

function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.subtest = subTest; //attach method subTest
}

function superTest() {
  return "superTest";
}
  
function subTest() {
  return "subTest";
}


 var newClass = new subClass();

  alert(newClass.subtest()); // yields "subTest"
  alert(newClass.supertest()); // yields "superTest"

So, now that you have seen how you can extend and reuse JavaScript objects it still leaves us with the question of should you use it. If you need to create code that needs to be reused or extended then it should be a JavaScript object. If you are just writing code that does a few lines of code that doesn't need to be reused or extended then procedural (a.k.a. typical function style code) style code is fine to use. So, the answer to the question is yes in many cases although there are times when it may be overkill.

The next post will take a look at how JavaScript will soon be changing once (or some would say if) ECMAScript 4 starts getting major browser support.

So, as always if you have any questions leave a comment or you can private message me once you add me to your buddy list (I will add you as a buddy as soon as I see the request) that is available once you login. Also, if you would like to write anything on this blog you can do so once you login by clicking on create content and then blog entry. The most interesting posts will be promoted to the home page.

many of the above code samples where taken from this post on JavaScript Kit.

Object Oriented JavaScript - Should You use It? - Part 1

Tagged:  

This post was part one of a three part series. You can read post two by clicking here and post three by clicking here.

If you have programmed any in JavaScript you are definitely familiar with the procedural method of coding, but you may not have seen many examples of object oriented JavaScript code. Since many JavaScript coders come from a scripting background, most practice a procedural programming style. However, if you have a C++, Java, C#, or any other object oriented programming language (you can program in an object oriented manner in languages such as PHP, however it is often not practiced) you will be interested in seeing how JavaScript object oriented programming differs from these coding languages.

Below is a simple example of a procedural coding style (this particular example just changes the name value of an anchor tag).

function RenameAnchor(anchorname, anchorid){
	document.getElementById(anchorid).name = anchorname;
}

We have all used this coding style many times in our JavaScript. One problem with this is that it will often cause you to copy and paste portions of code into other sections to extend them in different functions. While there is nothing necessarily wrong with this style in some instances there is a better way of coding.

Below is a simple example of an object oriented coding style (once again this particular example just changes the name value of an anchor tag).

var AnchorRename=new Object();
AnchorRename.CreateObject=function(anchorname, anchorid){
	this.anchorid=anchorid; //This is the id of the anchor element
	this.anchorname=anchorname;
	this.RenameAnchor(anchorname, anchorholerid);
};
AnchorRename.CreateObject.prototype={
	RenameAnchor:function(anchorname, anchorid){
		document.getElementById(anchorid).name = anchorname;
	}
};

While the above may at first look like it is just more complicated there are actually practical reasons for using this coding style. The most notible is re-usability. With an object you would create a new object and attach it to a variable name. You would create the new object as in the below code example.

var NewObject = new AnchorRename.RenameAnchor(variable1, variable2);

Now that you have a variable that is attached to the object you can access the object and its properties by referring to the variable, so you can re-use it much easier. Another nice feature of having this in an object is that it can be prototyped in new objects and extend the functionality of the object. While all of this is a little more in depth then I have time for right now I would be happy to answer any questions left in the comments of this post (or you can add me to your buddy list and private message me).

If you come from a C++ or Java background you will probably notice that this differs quite a bit from the object oriented style that you are used to. You will be happy to know that it looks like the next version of JavaScript should be more in-line to what you are used to. I'll be posting more on the new version of JavaScript when we are about to see major implementations of it.

Well, I know I haven't gone into much detail yet, but in my next two posts I will go over how exactly to code in an object oriented style (including different methods to accomplish this) and the how coding might change once ECMAScript 4 is fully adopted by the browsers. For now you can find a good tutorial regarding object oriented programming in JavaScript by clicking here.

JavaScript Game Library - Start Playing Your Games

Tagged:  

Well it is the weekend and time for some fun. I have found a good JavaScript Game Library. The library has some good 2-D gaming functionality. Including sprite animation (including properties for jumping and falling) tile handling for backgrounds and platforms.

Click here to go to the page where you can download the library.

There are also quite a few fun games that have been built with the library. Click here to go to the games.

Now that you have a JavaScript library for game creation you can extend it using Ajax (I would recommend the use of JSON instead of XML) so that you could make a network game. If you create a game let me know about it. I would love to play it.

videogamepic.jpg

DWR 3.0 vision

DWR 3.0 is going to be released soon. Following are vision from Joe, Founder of DWR

DWR 2.0 has been out for 6 months or so. At the time, I swore that the next release would be a small one, called 2.1. However it appears that I’m not good at swearing because there is lots in the next release - I think we’re going to have to call it 3.0.

Since 2.0, we've been working on the following adding support for JSON, Bayeux, images/binary file upload/download, a Hub with JMS/OAA support and more reverse ajax APIs. I also want to get some Gears integration going.

There are also a whole set of non-functional things to consider:
* Moving the website to directwebremoting.org
* Restart chasing CLAs, using a foundation CLA rather than a Getahead CLA
* Get some lawyer to create a CLA so Getahead can grant rights to the Foundation (or something similar)
* Get someone to pony up and let us move to SVN
* Unit tests

JSON support: One goal is a RESTian API so you can do something like this: http://example.com/dwr/json/ClassName/methodName?param1=fred;param2=jim and DWR will reply with a JSON structure containing the result of calling className.methodName("fred", "jim"); It would be good to support JSONP along with this. We might also allow POSTing of JSON structures, although I’m less convinced about this because it quickly gets DWR specific, and then what’s the point of a standard. Status - DWR has always used a superset of JSON that I like to call JavaScript. We do this to cope with recursive data, XML objects, and such like. I’ve done most of the work so that DWR can use the JSON subset, but not created the ‘handler’ to interface between the web and a JSON data structure.

Bayeux Support: Greg Wilkins (Jetty) committed some changes to DWR, which need some tweaks to get working properly. Greg still intends to complete this.

File/Image Upload and Download: This allows a Java method to return an AWT BufferedImage and have that image turn up in the page, or to take or return an InputStream and have that populated from a file upload or offered as a file download. I’ve had some bug reports that it doesn’t work with some browsers, also we need to find a way to report progress to a web page simply.

DWR Hub and integration with JMS and OpenAjax Hub: We have a hub, along with one way integration with JMS. The OpenAjax portion will be simple except for the getting the OpenAjax Hub to work smoothly with JMS part. Much of this work has not hit CVS yet, but will do soon.

Reverse Ajax Proxy API Generator: The goal with this is a program that will take JavaScript as input, and output a Java API which, when called, generates JavaScript to send to a browser. Some of this work has been tricky, but then meta-meta-programming was always bound to be hard. This currently mostly works with TIBCO GI, but more work will be needed to allow it to extract type information from other APIs.

DOM Manipulation Library: Currently this is limited to window.alert, mostly because I’m not sure how far to take it. There are a set of things like history, location, close, confirm that could be useful from a server, and that are not typically abstracted by libraries.

Gears Integration: I’ve not started this, but it needs to take higher priority than it currently does. It would be very cool if DWR would transparently detect Gears, and then allow some form of guaranteed delivery including resending of messages if the network disappears for a while.

Website: We need to get the DWR website moved away from the Getahead server, and onto Foundation servers. There will be some URLs to alter as part of this, and I don’t want to lose Google juice by doing it badly.
The documentation for DWR 2 was not up to the standards of 1.x, and while it has been getting better, we could still do more. One thing that has held this back has been lack of a DWR wiki. I hope we can fix this with the server move.

Source Repo: We are currently using CVS hosted by java.net (which is a collab.net instance - yuck). They support SVN, but want to charge me a few hundred dollars to upgrade. Maybe the Foundation can either ridicule them into submission or pay the few hundred dollars for the meta-data so we can host the repo. ourselves. The latter option is probably better.

Unit Tests: I've been trying for ages to find a way to automatically test with multiple browsers and servers. WebDriver looked good for a while, but it doesn't look like the project is going anywhere particularly quickly, so I'm back trying to get Selenium to act in a sane way.

Simple "Class" Instantiation in Javascript

Tagged:  

John Resig has pulled out his bag-o-tricks and shared another golden nugget with us.

This time he shares a pattern to simplify Class-style instantiation of a function in JavaScript.

In a nutshell, John takes this example:

function User(first, last){
    this.name = first + " " + last;
}

var user = new User("John", "Resig");

and shows how it can become a debugging nightmare and why it's not as efficient and flexible as other methods. Most importantly, he covers why the use of "this" in a function requires that it be instantiated and not called directly.

Then, he gives us the solution that solves the problems raised in the code above with this example:

function User(first, last){
  if ( this instanceof User ) {
    this.name = first + " " + last;
  } else
    return new User(first, last);
}

Then he wraps this together into a generic class constructor that can be reused to build these types of functions:

// makeClass - By John Resig (MIT Licensed)
function makeClass(){
  return function(args){
    if ( this instanceof arguments.callee ) {
      if ( typeof this.init == "function" )
        this.init.apply( this, args );
    } else
      return new arguments.callee( arguments );
  };
}

Refactoring the original example code at the top of this post with this generic class constructor would produce:

var User = makeClass();
User.prototype.init = function(first, last){
  this.name = first + " " + last;
};
var user = User("John", "Resig");
user.name
// => "John Resig" 

Click here to read John's post in which he does a great job explaining the code above (including the pitfalls of the original example and how the solution works).

JavaScript Array Remove Method

Tagged:  

John Resig just published a handy little JavaScript method to remove elements from an array.

Here's his method:

   1. // Array Remove - By John Resig (MIT Licensed)
   2. Array.prototype.remove = function(from, to) {
   3.   var rest = this.slice((to || from) + 1 || this.length);
   4.   this.length = from < 0 ? this.length + from : from;
   5.   return this.push.apply(this, rest);
   6. };

And here are some examples of its use:


   1. // Remove the second item from the array
   2. array.remove(1);
   3. // Remove the second-to-last item from the array
   4. array.remove(-2);
   5. // Remove the second and third items from the array
   6. array.remove(1,2);
   7. // Remove the last and second-to-last items from the array
   8. array.remove(-2,-1);

Here are the goals he had for the method:

  • It had to add an extra method to an array object that would allow me to remove an item by index (e.g. array.remove(1) to remove the second item).
  • It had to be able to remove items by negative index (e.g. array.remove(-1) to remove the last item in the array).
  • It had to be able to remove a group of items by index, and negative index (e.g. array.remove(0,2) to remove the first three items and array.remove(-2,-1) to remove the last two items).
  • It had to be destructive (modifying the original array).
  • It had to behave like other destructive array methods (returning the new array length - like how push and unshift work).

To get more information about this method, click here to visit John's blog.

Ext 2.0 Final Released

If you haven't heard of Ext before, click here to learn all about it.

Here's the annoucement right from the Ext JS Blog:

The Ext team is proud to announce that the official release of Ext v2.0 is available for download. This new version of the Ext framework is the culmination of many long hours of work and dedication by the Ext Core team as well as our community of testers and supporters. Ext 2.0 is a dramatic step forward from all previous versions of Ext, providing increased performance, ease of configurations, flexibility and UI capabilities.

We’ve also made learning how to use Ext much easier with a completely revamped document center and expanded & better organized samples. All of this without a significant library size increase in this new version.

New features include:

  • Grouping & Group Summary
  • Ext 2.0 introduces highly configurable single-level column grouping capabilities as well as summary rollups at the group level.

  • Scrolling Tabs
  • The new Ext 2.0 scrolling tabs are truly amazing and provide for a much more flexible UI then traditional static-based tabs.

  • Anchor Layout
  • The team extended the FormPanel component to allow form controls (and other components) to be anchored to a specific size within a specific container.

  • Column Tree
  • The Ext tree panel can be customized to add support for columns in the nodes.

There's also a New API Documentation Center, including:

Click here to download Ext 2.0

Syndicate content