Libraries

JavaScript Step Carousel Viewer

Tagged:  

Dynamic Drive has posted a jQuery-based Step Carousel script that enables you to display images or rich HTML by side scrolling them left or right. Besides supporting sequential scrolling, it also has the capability to jump to any scroll item or scroll x items at a time. The script has two public methods, two custom event handlers, and three "status" variables to provide more control. It's also able to handle content defined directly inline on the page or loaded dynamically with Ajax. Content is simply contained in DIVs with a common CSS class. For implementation details, visit Dynamic Drive.



Visit the Step Carousel Homepage for more information, demos, and to download the script.

MooCrop - a JavaScript Image Cropping UI

Nathan White has developed an image cropping library called MooCrop, built with the MooTools JavaScript framework. MooCrop can be combined with a server side script to provide image manipulation functionality in your apps. The library weighs in just under 11K and totals for about 35K when you add in the YUI compressed MooTools framework.

Resize the crop area below and double-click it to see the result on the right:

Here are some features of the MooCrop class as described on its homepage:

  • Completely customizable CSS styling
  • Detects and handles multiple CSS box models
  • Allows for masking to be toggled
  • Ability to hide resize handles during drag
  • Custom events for your own modification
  • Relative based postioning rather then absolute (should handle overflow properly)
  • Works and retains layouts on floating images.
  • Resize from 8 different directions
  • Ability to set minimium size limit
  • Cleans up nicely, leaving your DOM in its original state when removed.
  • Fast!

Visit the MooCrop homepage for more demos, information, and downloads

YouTube Data API Changes and Player API

If you haven't heard the big news yet, the YouTube Data API has been updated and the YouTube Player APIs have been released. The APIs look very interesting with some much wanted features.

The below is the big news from the YouTube Blog.

Here's the sound byte: We now support upload, other write operations, and internationalized standard feeds. (And there was much rejoicing!) We're also introducing player APIs and a chromeless player -- a barebones player SWF that's fully customizable and controllable using the player APIs.

The Data API now allows for reading (nothing new), writing and uploading of data (the latter two are the big news). The API allows for you to do many things that can be done in YouTube, such as add comments about a video or upload videos to YouTube. Libraries for the API are available for Java and PHP (sorry Ruby developers at least for now).

You can read more about the Data API here.

The Player APIs now offer a Flash (Actionscript 2.0) API and a JavaScript API to allow more control over the player. The JavaScript API and Flash API are very similar (which makes since as they are both based on ECMA Script). The APIs have some very powerful hooks into the videos. My personal favorite hook is player.getPlayerState() which returns the state of the player. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).

You can read about the JavaScript API here and the Flash API here (note that the Flash API is almost exactly the same as the JavaScript API, so you will need to read both references if you are going to use the Flash API).

Perhaps Even bigger news is the release of the chromeless player. Below is an excerpt about the chromeless player from reference.

Getting Started

First off, you need a developer key. To register for one, visit the registration page.

The chromeless player consists of two SWF files. apiplayer.SWF contains the actual video playing functionality. cl.SWF is a loader SWF that loads apiplayer.SWF and exposes the player's API functions. It also provides security sandbox restrictions for the apiplayer.SWF, so loading SWFs cannot access elements inside the player directly.

The player can be controlled via two methods — by loading the SWF into another SWF (or Flash website, etc.), or by embedding it directly in an HTML page and using JavaScript to control the player. The JavaScript controls are identical to the embedded player's JavaScript API.

The URL to load the chromeless player SWF is:

http://gdata.youtube.com/apiplayer?key=DEV_KEY

Functions

The following operations are available in addition to the ones listed in the JavaScript API documentation.

loadVideoById(videoId:String, startSeconds:Number):Void
Load the specified video and starts playing the video. If startSeconds (number can be a float) is specified, the video will start from the closest keyframe to the specified time.
cueVideoById(videoId:String, startSeconds:Number):Void
Loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until playVideo() or seekTo() is called. startSeconds accepts a float/integer and specifies the time that the video should start playing from when playVideo() is called. If you specify startSeconds and then call seekTo(), the startSeconds is forgotten and the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).
setSize(width:Number, height:Number):Void
Sets the size of the chromeless player. This method should be used in favor of setting the width + height of the MovieClip directly. Note that this method does not constrain the proportions of the video player, so you will need to maintain a 4:3 aspect ratio. When embedding the player directly in HTML, the size is updated automatically to the Stage.width and Stage.height values, so there is no need to call setSize() when embedding the chromeless player directly into an HTML page. The default size of the SWF when loaded into another SWF is 320px by 240px.

You can read more about the new features at the YouTube API Blog.

I think that these new feature really make it possible to make some great mash-ups with YouTube. If you create a cool mash-up using some of the new features of the API or use the the Player APIs or use the chromeless player then I would love to hear about it (you can leave it in the comments or you can write a blog post about it using your free Ajaxonomy account.

jQuery Tutorials for Designers

jQuery is a great library for animation and Ajax calls. As with any JavaScript library there are different objects and name spaces to learn. Well, over at Web Designer Wall they have put together a good tutorial about using jQuery. The tutorial is written from a designers stand point, but even an experienced hard-core web programmer can find this tutorial useful.

Below is an excerpt from the post:

How jQuery works?

First you need to download a copy of jQuery and insert it in your html page (preferably within the <head> tag). Then you need to write functions to tell jQuery what to do. The diagram below explains the detail how jQuery work:

how jquery works

How to get the element?

Writing jQuery function is relatively easy (thanks to the wonderful documentation). The key point you have to learn is how to get the exact element that you want to apply the effects.

  • $("#header") = get the element with id="header"
  • $("h3") = get all <h3> element
  • $("div#content .photo") = get all element with class="photo" nested in the <div id="content">
  • $("ul li") = get all <li> element nested in all <ul>
  • $("ul li:first") = get only the first <li> element of the <ul>

1. Simple slide panel

Let’s start by doing a simple slide panel. You’ve probably seen a lot of this, where you click on a link and a panel slide up/down. (view demo)

sample

When an elment with class="btn-slide" is clicked, it will slideToggle (up/down) the <div id="panel"> element and then toggle a CSS class="active" to the <a class="btn-slide"> element. The .active class will toggle the background position of the arrow image (by CSS).

$(document).ready(function(){

	$(".btn-slide").click(function(){
	  $("#panel").slideToggle("slow");
	  $(this).toggleClass("active");
	});

});

2. Simple disappearing effect

This sample will show you how to make something disappear when an image button is clicked. (view demo)

sample

When the <img class="delete"> is clicked, it will find its parent element <div class="pane"> and animate its opacity=hide with slow speed.

$(document).ready(function(){

	$(".pane .delete").click(function(){
	  $(this).parents(".pane").animate({ opacity: "hide" }, "slow");
	});

});

3 Chain-able transition effects

Now let’s see the power of jQuery’s chainability. With just several lines of code, I can make the box fly around with scaling and fading transition. (view demo)

sample

Line 1: when the <a class="run"> is clicked

Line 2: animate the <div id="box"> opacity=0.1, left property until it reaches 400px, with speed 1200 (milliseconds)
Line 3: then opacity=0.4, top=160px, height=20, width=20, with speed "slow"
Line 4: then opacity=1, left=0, height=100, width=100, with speed "slow"

Line 5: then opacity=1, left=0, height=100, width=100, with speed "slow"
Line 6: then top=0, with speed "fast"
Line 7: then slideUp (default speed = "normal")
Line 8: then slideDown, with speed "slow"

Line 9: return false will prevent the browser jump to the link anchor

$(document).ready(function(){

	$(".run").click(function(){

	  $("#box").animate({opacity: "0.1", left: "+=400"}, 1200)
	  .animate({opacity: "0.4", top: "+=160", height: "20", width: "20"}, "slow")
	  .animate({opacity: "1", left: "0", height: "100", width: "100"}, "slow")
	  .animate({top: "0"}, "fast")
	  .slideUp()
	  .slideDown("slow")
	  return false;

	});

});

4a. Accordion #1

Here is a sample of accordion. (view demo)

sample

The first line will add a CSS class "active" to the first <H3> element within the <div class="accordion"> (the "active" class will shift the background position of the arrow icon). The second line will hide all the <p> element that is not the first within the <div class="accordion">.

When the <h3> element is clicked, it will slideToggle the next <p> and slideUp all its siblings, then toggle the class="active".

$(document).ready(function(){

	$(".accordion h3:first").addClass("active");
	$(".accordion p:not(:first)").hide();

	$(".accordion h3").click(function(){

	  $(this).next("p").slideToggle("slow")
	  .siblings("p:visible").slideUp("slow");
	  $(this).toggleClass("active");
	  $(this).siblings("h3").removeClass("active");

	});

});

4b. Accordion #2

This example is very similar to accordion#1, but it will let you specify which panel to open as default. (view demo)

In the CSS stylesheet, set .accordion p to display:none. Now suppose you want to open the third panel as default. You can write as $(".accordion2 p").eq(2).show(); (eq = equal). Note that the indexing starts at zero.

$(document).ready(function(){

	$(".accordion2 h3").eq(2).addClass("active");
	$(".accordion2 p").eq(2).show();

	$(".accordion2 h3").click(function(){
	  $(this).next("p").slideToggle("slow")
	  .siblings("p:visible").slideUp("slow");
	  $(this).toggleClass("active");
	  $(this).siblings("h3").removeClass("active");
	});

});

You can read the full post here.
You can also view the demo here or download the demo code here.

jQuery is one library that I really recommend using. The library is very well written and is pretty easy to learn fairly quickly. If you haven't used the library before this is a good tutorial to start with.

SWFUpload v2.1.0 Beta

Earlier this month, a new beta release of SWFUpload was posted over at SWFUpload.org. This release reduces the amount of code in SWFUpload, improves code reuse, fixes bugs, and adds some new features. All JavaScript in the project is said to have been run through JSLint.com to improve general quality and consistency. For a full change log, click here.

For those of you not familiar with SWFUpload, it is a small JavaScript/Flash library to handle file uploads. Here's a short description of how it works:

SWFUpoad uses a hidden Flash movie to handle file selection and upload. JavaScript is used to activate the file selection dialog. The file selection dialog is configured to allow the user select to a single file or to multiple files. The file types can be restricted so users only select the appropriate files (e.g., *.jpg;*.gif).

Once files are selected each is processed to check for valid file extensions and that the file is within size limits. Flash calls several pre-defined JavaScript callback functions which the developer overrides in order to update the page's UI so users can see file progress or errors.

The uploaded file is submitted separately from the rest of the page and form. Each file is uploaded individually which keeps the server-side upload handling script simple as it only ever has to handle a single uploaded file at a time. Since Flash is providing the upload service the page does not have to be reloaded. The usage pattern for SWFUpload is more like that of an AJAX application than that of standard HTML form. Often the server-side script that receives the uploaded file is different than the target of the page's form. The page's form will be processed separately from the file upload.

Check out some demos

Click here to download

Upgrading to Prototype 1.6 just got easier

Here's some good news for those of you who still need to upgrade your Prototype 1.5 code to Prototype 1.6. Tobie Langel, a core developer on the Prototype team, has developed a script that will warn you of any deprecations or API changes between versions. If you don't know why you should upgrade to 1.6, check out the release info for version 1.6, including the changelog and release notes for 1.6.0_rc0 and 1.6.0_rc1. The script is used with Firebug and is Firefox only, but once you've upgraded, you're good to go in all browsers.

Using the script is easy. To migrate a page from 1.5 to 1.6:

  1. Find the script tag that references prototype.js. Change the path to point to the 1.6.0.2 version (or else overwrite the existing prototype.js with the new version).
  2. On the very next line, add a script tag that references deprecation.js.
  3. Develop your app as normal.

When your code calls a method that’s been deprecated, replaced, or modified, the script will log a warning or error to your Firebug console. Clicking its hyperlink will take you to the deprecation script itself, which isn’t all that helpful; but the message itself will contain a stack trace that points to the source of the error.

Download the deprecation script.

Read more about the script over at the Prototype blog.

Accessing JSON Web Services with the Google Web Toolkit

Over at GWT Site they have written a good post about using the Google Web Toolkit with JSON Web Services. Since JSON is fast becoming a standard for web services that are cross domain and GWT is a heavily used development tool this is a useful post.

below is an excerpt from the post.

The main difficulty when trying to talk to some web service on another server is getting past your web browser’s Same-Origin Policy. This basically says that you may only make calls to the same domain as the page you are on. This is good for security reasons, but inconvenient for you as a developer as it eliminates the use of GWT’s HTTP library functions to achieve what we want to do. One way to get around this is to call a web service through a javascript <script> tag which bypasses this problem. In his book, Google Web Toolkit Applications, Ryan Dewsbury actually explains this technique in more detail and provides a class called JSONRequest which handles all the hard work for us. JSON is one of the more popular data formats, so most web services support it. Lets leverage Ryan’s code and take a quick look at how it works.

public class JSONRequest {
  public static void get(String url, JSONRequestHandler handler) {
    String callbackName = "JSONCallback"+handler.hashCode();
    get( url+callbackName, callbackName, handler );
  }	
  public static void get(String url, String callbackName, JSONRequestHandler handler ) {
    createCallbackFunction( handler, callbackName );
    addScript(url);
  }
  public static native void addScript(String url) /*-{
    var scr = document.createElement("script");
    scr.setAttribute("language", "JavaScript");
    scr.setAttribute("src", url);
    document.getElementsByTagName("body")[0].appendChild(scr);
  }-*/;
  private native static void createCallbackFunction( JSONRequestHandler obj, String callbackName)/*-{
    tmpcallback = function(j) {
      obj.@com.gwtsite.client.util.JSONRequestHandler::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
    };
    eval( "window." + callbackName + "=tmpcallback" );
  }-*/;
}

To make our request we call the get method with the web service url, and an implementation of the JSONRequestHandler interface. This interface has one method called onRequestComplete(String json). This is where you’ll handle the JSON formatted data once it comes back from the server. When calling a service from within a script tag, we need to specify the name of a callback function in the request. Most services let you specify the name yourself, so the first get method generates a callback name for you. The createCallback method is a JSNI method that simply calls your JSONRequestHandler implementation when the call returns via the callback name. Note, if you use this class, to make sure and change the package name for the JSONRequestHandler call to the correct location. Finally, the get method will call the addScript function which is responsible for embedding the <script> tag on your page and setting its src attribute to the web service url.

You can read the full post here.

Since I am a fan of both JSON and GWT I enjoy seeing good posts about using these two technologies. I recommend this post for any Java developer that wants to make Ajax applications using Web Services.

IncludeJS - include and compress JavaScript easily

Justin Meyer has been working on a JavaScript library named IncludeJS and has released a 0.1 alpha 1 Developer package. IncludeJS lets developers include and compress JavaScript files easily. The hope for the library is "to bridge the gap between frameworks like jQuery/Prototype which guess at what you will most likely need, and frameworks like MooTools, which are great if you know exactly what you want and don't need to look in the source."

IncludeJS was originally a component of JavaScriptMVC - an open source JavaScript Model-View-Controller framework. The framework is going through some major changes and individual components are being extracted to make each individually useful.

Features of IncludeJS:

Relative paths.

Instead of including files relative to the current page's url,
IncludeJS includes files relative to your JavaScript files' urls.
Forget about scanning the page's script tags for your library's path.
IncludeJS lets you organize your scripts however you want.

Dynamic compression.

IncludeJS uses Dean Edwards packer
to automatically compress your
JavaScripts. Unlike server-side compression scripts,
compression is determined at runtime. This makes
it easy to compress large libraries with optional plugins.

Highlights.

- Consistant include order (last-in-first-out)
- FF 1.5+, IE 6+, Opera 9, Safari 3.
- Works with libraries like Prototype and jQuery.
- MIT license.
- 3 KB compressed.
- Files visible in Firebug.

Usage

1) Include the library in your page

<script src="include.js" type="text/javascript">
</script>

2) Include JavaScript files with the include function, files are relative to the including file and will be included in LIFO [last-in-first-out] order.

<script type="text/javascript">
   include( 'javascripts/prototype',
            'javascripts/myapplication'
   )
</script>

3) Compress your app by adding the line:

include.setup('compress')

before your includes, after the page loads you're presented with a compressed version of the code.

<script type="text/javascript">
   include.setup('compress')
   include( 'javascripts/prototype',
            'javascripts/myapplication'

   )
</script>

4) Run it! After you've saved the compressed version of the code, change the "compress" argument to "production" and specify the path to the newly created library as a second argument.

<script type="text/javascript">
   include.setup('production','path/to/prod')
   include( 'javascripts/prototype',
            'javascripts/myapplication'
   )

</script>

Visit the IncludeJS Homepage

Check out the demo over at JavaScriptMVC.com

Cross Browser Sound in JavaScript

When working on an upcoming project I had the need to play sound through JavaScript. The method had to be cross-browser compatible, so I couldn't use any IE only calls.

Happily, I found a nice API called SoundManager2 which uses Flash to play the sound and is called through JavaScript. The API is very easy to use and below is a sample of how to use it.

The below code would be put inside the head tag of your web page.

<script type="text/javascript" src="soundmanager2-jsmin.js"></script>
<script type="text/javascript">

soundManager.url = 'soundmanager2.swf'; // override default SWF url
soundManager.debugMode = false;
soundManager.consoleOnly = false;

soundManager.onload = function() {
  // soundManager is initialised, ready to use. Create a sound for this demo page.
  soundManager.createSound('aDrumSound','button-0.mp3');
}</script>

The part of the above code that you will be most interested in is the last line. The soundManager.createSound('aDrumSound','button-0.mp3'); is what actually loads the sound file.

The below code will cause the sound to play.

soundManager.play('aDrumSound');

You can go to the project page by clicking here and get more information about the API. Also, you can download the files needed to use the API (including documentation and demos) here.

The library would be very useful in many applications including JavaScript games. If you create any cool applications using the API I would love to hear about it. You can post a blog entry about it when you create a free account (once you login just click on "Create content" => "Blog Entry") on this blog.

Tatami integrates the Google Web Toolkit and the DOJO framework

The Tatami project is an attempt to integrate the Google Web Toolkit (GWT) and the DOJO JavaScript framework. Tatami pulls in DOJO's rich widgets and utilities (like fisheye, slider, drag and drop functionality) and makes them accessible to the GWT as widgets and helpers. Tatami is compatible with the GWT 1.4 final version.

Check out the demo (may run slowly because files are being served from SVN)

Last month's release of Tatami-1.1 contained some new features, they are:

* DOJO 1.0 wrapped

* DropdownDatePicker and DropdownTimePicker with validation.

* Slider with labels an rule mark.

* The GFX package of DOJO wrapped. (Circle, Rectangle, Path, scaling...)

Visit the Tatami project homepage.

Syndicate content