Archive

Posts Tagged ‘Javascript’

Richard Stallman: Free the Javascript

March 24th, 2009 No comments

gnu

Richard Stallman, founder of the GNU project and the Free Software Foundation, warns against the “trap” of running web apps whose Javascript is not licensed.

Most web apps have source code that is “open” as far as being available in source code form (unless it’s obfuscated/compressed/generated). Indeed, this openness is a major factor in the rapid growth in our understanding of Ajax; formerly obscure tricks and techniques could be studied in their full visible source code glory, and patterns could be systematically mined from the huge corpus of real-world Javascript code out there. However, most of the Javascript code in web apps assumes a conventional copyright license, and Stallman’s complaint is that it should instead be issued under free software licenses.

Stallman suggests that free Javascript licenses should be one of the features of open web standards:

A strong movement has developed that calls for web sites to communicate only through formats and protocols that are free (some say “open”); that is to say, whose documentation is published and which anyone is free to implement. With the presence of programs in web pages, that criterion is necessary, but not sufficient. Javascript itself, as a format, is free, and use of Javascript in a web site is not necessarily bad. However, as we’ve seen above, it also isn’t necessarily ok. When the site transmits a program to the user, it is not enough for the program to be written in a documented and unencumbered language; that program must be free, too. “Only free programs transmitted to the user” must become part of the criterion for proper behavior by web sites.

Silently loading and running non-free programs is one among several issues raised by “web applications”. The term “web application” was designed to disregard the fundamental distinction between software delivered to users and software running on the server. It can refer to a specialized client program running in a browser; it can refer to specialized server software; it can refer to a specialized client program that works hand in hand with specialized server software. The client and server sides raise different ethical issues, even if they are so closely integrated that they arguably form parts of a single program. This article addresses only the issue of the client-side software. We are addressing the server issue separately.

The last comment is a reminder of the Affero GPL, which (among other things) obligates web developers to publish their server-side code if it uses AGPL software. Thus, the Free Software Foundation is targeting the full web app stack – server-side code and Javascript client code.

The article goes on to propose a Greasemonkey-related means of substituting in free code for Javascript web apps; as well as suggesting developers should open source their web apps, Stallman is proposing a world in which free software projects would arise to act as alternative web clients to those apps that don’t open source.

Categories: Programming Tags:

TraceVis: Getting some eyes into TraceMonkey

March 24th, 2009 No comments

David Mandelin has announced“a visualization of TraceMonkey performance, with the goal of revealing what the JS VM is doing, and why it runs certain programs fast or slow, so we can figure out how to make the slow ones fast too.”

David starts off explaining what TraceMonkey is about, and pieces together the activities:

  • When TM starts running a program, it always starts by interpreting the program, exactly as in the non-tracing JS engine.
  • When execution reaches a point where TM might want to start a compiled trace, TM spends a bit of time monitoring the execution: checking to see if it already has a compiled region, counting the number of times passed, and deciding whether to start a trace. Monitoring is a kind of overhead: while monitoring, TM isn’t running the user’s program, but monitoring is a necessary cost of finding and optimizing traces.
  • If TM does decide to create a new compiled trace, it runs in the interpreter while recording the trace, including operations and types of values. During this time, it is running user code a little slower than the basic interpreter.
  • When the trace is finished, TM compiles the trace to native code. This is another form of overhead.
  • As I mentioned above, as part of monitoring, TM checks to see if it already has a compiled native trace starting at the current point. If so, TM selects the right trace and prepares to run it, which I call executing the trace. This is a third form of overhead.
  • Finally, TM can be running native code compiled previously. Compiled native traces run 2-20x faster than the interpreter, with a typical speedup factor of about 2.5.

With these new eyes, David walks through various benchmarks to see how they are effected. Now that it is easier to see what is going on, the team should be able to optimize even faster.

Categories: Programming Tags: ,

Ghosts in the machine – avoid using window.sun in Firefox as it starts the Java engine!

March 24th, 2009 No comments

Sometimes you find leftovers of old technology in browsers that blow your mind. One of these “ghost in the machine” problems exists in Firefox: if you use window.sun or function sun() in JavaScript you effectively start the Java VM.

There are a few “magic” properties on Mozilla’s DOMWindow interface for supporting LiveConnect that will initialize the Java plugin and all the baggage that comes with it (which, with modern Java plugins, means launching java.exe as a subprocess). Looking up these properties on the window object is all it takes.

There are a few more of these still in the Mozilla source code and they are part of the old Netscape LiveConnect engine. They are:

  • java
  • Packages
  • netscape
  • sun
  • JavaClass
  • JavaArray
  • JavaMember

Avoid these at all cost lest you want the performance of your JavaScript to be like a Java Applet.

Namespace.js: take a wild guess….

March 24th, 2009 No comments

Let’s lead with code:

PLAIN TEXT

JAVASCRIPT:

  1. Namespace(‘foo.bar’);

  2. foo.bar.myFunction = function() {};

  3. Namespace(‘com.example’, {

  4.    MyClass: function() { return {}; }

  5. });

  6. var obj = new com.example.MyClass();

  7. Namespace.use(‘com.example.MyClass’);

  8. var obj2 = new MyClass();

  9. // include com/example/RemoteClass.js

  10. Namespace.include(‘com.example.RemoteClass’);

  11. var obj3 = new com.example.RemoteClass();

  12. Namespace.registerNativeExtensions();

  13. ‘com.foo.bar’.namespace();

Reading the code above is probably all you need to know about the new, library independant, JavaScript library Namespace.js, created by Maxime Bouroumeau-Fuseau.

The goals for the library are:

  • Simple API
  • Framework independent
  • Remote file loading (synchronously or async)
  • Tested against Firefox 3.x, Safari 3.x, IE 6/7 and Opera 9.5
  • Highly configurable
  • Events
  • Optionally add methods to native objects

You can see more in the How To.

Ext JS and Adobe AIR

March 24th, 2009 No comments

As we’ve been exploring ways to take Bespin to the desktop, we’ve looked closely at some of the single-site browser technologies and their individual APIs to work out which platform we favor. As we went through this exercise, Adobe AIR really impressed us with the richness of its JavaScript APIs which wrap native APIs (as well as the accompanying documentation).

There’s no other competing JavaScript API that we’ve seen that comes close to this level of comprehensiveness (please correct us in the comments in we’re wrong).

We weren’t able to use AIR as its implementation of <canvas> is a bit old, but we’re excited to play with it as soon as we can.

Ext JS and Pixel Bender Explorer

 

bender

 

We’re not the only ones who have been playing with AIR. Aaron Conran from the Ext JS crew blogged about Pixel Bender Explorer , an AIR app they wrote to demonstrate how to integrate Ext JS with AIR’s Pixel Bender technology that lets you apply pretty amazing effects to interfaces.

Pixel Bender can spruce up an Ext.air application by adding custom animations to wow your users. However, you should be cautious about the over-use of these filters throughout your application. For a good example of how effective these filters and animations can be to provide proper user feedback you should check Adobe’s signature sample BlackBookSafe. Each time an animation occurs it is clear why it happened, not a surprise to the user and adds character to the application. When using these animations you should strive for the same goal, not to surprise your user, but to impress them.

Categories: Designing, Programming Tags: ,

Rendering Text With Javascript, Canvas And VML

March 21st, 2009 No comments

Instead of creating images or using flash just to show your site’s graphic text in the font you want, you can use typeface.js and write in plain HTML and CSS, just as if your visitors had the font installed locally.

Typeface.js uses browsers’ vector drawing capabilites to draw text in HTML documents. The typeface.js project has two components: the perl module for converting fonts, and the javascript library for drawing in the browser. The perl module extracts glyph outline information from truetype fonts and writes that data in JSON format. The javascript library then traverses the HTML document and renders text using <canvas> or VML to draw the glyphs.

This code is and always will be free and open source. This includes both the typeface.js javascript library, as well as the perl module with functionality to convert truetype fonts to typeface ones.

 

typeface

Categories: Others, Programming Tags: , , ,

TinyTable – Easy to Use Javascript Table Sorter

March 21st, 2009 No comments

TinyTable is a JavaScript table sorter script is easy to use and feature packed at only 2.5KB. There are many features great include column highlighting, optional pagination, support for links, date/link parsing, alternate row highlighting, header class toggling, auto data type recognition and selective column sorting. Also, the table styling is completely customizable via the CSS.

TinyTable has been tested in Firefox 2/3, IE 6/7/8, Opera, Safari and Chrome. This script is available free of charge any project, personal or commercial, under the creative commons license and is offered AS-IS, no free support provided.

TinyTable

Odometer Style Javascript Counter in Mootools

March 21st, 2009 No comments

UvumiTools Odometer is an odometer style Javascript counter, where you can actually see the numbers spining. It is a Mootools plugin requires no Flash, it’s all CSS and Javascript. It can serve multiple purposes, like a live visit counter or a cashier style counter on a shopping website. It can be anything that involves updating a numeric value dynamically.

UvumiTools Odometer can be be updated manually or you can set it so it periodically calls a server script via an AJAX request and uses the returned value as a new target. This is also easy, you just need to specify the URL to that script when you initialize the counter. If the difference between two values is too big and the counter is spinning for several minutes. You can directly jump to the targeted value by simply double-clicking on the counter.

 

odometer

Categories: Webmaster Tools Tags: ,

Create a Nice, Lightweight JavaScript Tooltip

March 21st, 2009 No comments

Editor’s note: This tutorial was written by Michael Leigeber, a web designer and .NET developer who runs the Leigeber Web Development Blog- a blog that’s setting the blogging community buzzing with his beautiful, lightweight JavaScript solutions.

Introduction

To begin, create the 3 files needed for this tutorial (index.html, style.css and script.js) and include the stylesheet and the script from index.html. To make things easy the starter files are available by clicking here. 

The most important things to remember when writing JavaScript are to keep the code simple and to script logically. The first thing that needs to be established is precisely what you would like the script to accomplish. Based on the desired functionality it then helps to create a diagram or flow description for any complex script before you get into the code. Doing so can help streamline the logic and keep the script clean.

What we are trying to accomplish…

Create a lightweight script that fades a tooltip with rounded corners in relation to the cursor position.

How does the script need to flow…
  1. Setup the namespace and global variables.
  2. Create a function to display the tooltip that takes two variables, the string to display and an optional width integer.
  3. When the function is called build the tooltip markup if it does not exist and register an onmousemove listener to position the tooltip. Insert the tooltip content into the tooltip and call a function to incrementally fade the tooltip to the target opacity.
  4. On the mouseout event of a “hotspot” reference a function that calls the fade function to incrementally hide the tooltip.

Let’s begin by setting up the JavaScript file. We want to create a namespace to encapsulate the functionality of our script. By doing so, we virtually eliminate the possibility of a conflict with some other script or framework.

var tooltip(){
	return{};
}();

Next, we need to add any variables we want to include on the global level of the namespace. By setting these variables globally we can access them in any of the child functions and quickly change them without sorting through the code.

  • id (string) – id of the tooltip
  • top (integer) – number of pixels to offset the tooltip from the top of the cursor
  • left (integer) – offset to the right of the cursor
  • maxw (integer) – maximum width in pixels of the tooltip
  • speed (integer) – value to increment the tooltip opacity during transition
  • timer (integer) – represents the speed at which the fade function in performed
  • endalpha (integer) – target opacity of the tooltip
  • alpha (integer) – current alpha of the tooltip
  • tt, t, c, b, h – these represent global variables to be set later
  • ie (boolean) – global variable based on browser vendor
 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;

We need to determine how we want the tooltip to look so we can figure out how to build out the elements to add to the DOM… a rectangle with rounded corners on the top and right corners only. To accomplish this we need a wrapper div and then three nested divs. We can style the divs with the CSS. The markup should look something like this once generated.

<div id="tt">
	<div id="tttop"> </div>
	<div id="ttcont"> </div>
	<div id="ttbot"> </div>
</div>

The first function we will name ‘show’ and it will be accessible by calling tooltip.show(). It will need to take two parameters… the content string and an optional width integer. To begin, it will need to check and see if the tooltip has been added to the DOM yet. If it does not exist the divs need to be built and added to the body. Either way the innerHTML of the contentdiv will need to be set to the content parameter, the height and width set and the fade function set to a timer.

show:function(v,w){
if(tt == null){
 tt  = document.createElement('div');
 tt.setAttribute('id',id);
 t  = document.createElement('div');
 t.setAttribute('id',id  + 'top');
 c  = document.createElement('div');
 c.setAttribute('id',id  + 'cont');
 b  = document.createElement('div');
 b.setAttribute('id',id  + 'bot');
 tt.appendChild(t);
 tt.appendChild(c);
 tt.appendChild(b);
 document.body.appendChild(tt);
 tt.style.opacity  = 0;
 tt.style.filter  = 'alpha(opacity=0)';
 document.onmousemove  = this.pos;
}
tt.style.display  = 'block';
c.innerHTML =  v;
tt.style.width  = w ? w + 'px' : 'auto';

if(!w  && ie){
 t.style.display  = 'none';
 b.style.display  = 'none';
 tt.style.width  = tt.offsetWidth;
 t.style.display  = 'block';
 b.style.display  = 'block';
}

if(tt.offsetWidth  > maxw){tt.style.width = maxw + 'px'}

h =  parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer =  setInterval(function(){tooltip.fade(1)},timer);
},

The next function we need is the position function that will set the top and left values of the tooltip as the cursor moves. First we calculate the position based on the browser and then we set the values taking into consideration the global offset variables.

pos:function(e){
 var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
 var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
 tt.style.top = (u - height) + 'px';
 tt.style.left = (l + left) + 'px';
},

Next we need to create a function that will fade the tooltip from its current opacity to the target opacity based on the direction variable that is passed to it.

fade:function(d){
 var a = alpha;
 if((a !=  endalpha && d == 1) || (a != 0 && d == -1)){
   var  i = speed;
   if(endalpha  - a < speed && d == 1){
      i  = endalpha - a;
   } else  if(alpha < speed && d == -1){
      i  = a;
  }
  alpha  = a + (i * d);
  tt.style.opacity  = alpha * .01;
  tt.style.filter  = 'alpha(opacity=' + alpha + ')';
   }else{
     clearInterval(tt.timer);
     if(d  == -1){
     tt.style.display  = 'none';
  }
 }
},

Finally the function to hide the tooltip onmouseout.

hide:function(){
	clearInterval(tt.timer);
	tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
}

That completes the JavaScript. We are left with a 2kb script that is compatible with IE6, IE7, Firefox, Opera and Safari.

Here is the full script
var tooltip=function(){
 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
   if(tt == null){
    tt = document.createElement('div');
    tt.setAttribute('id',id);
    t = document.createElement('div');
    t.setAttribute('id',id + 'top');
    c = document.createElement('div');
    c.setAttribute('id',id + 'cont');
    b = document.createElement('div');
    b.setAttribute('id',id + 'bot');
    tt.appendChild(t);
    tt.appendChild(c);
    tt.appendChild(b);
    document.body.appendChild(tt);
    tt.style.opacity = 0;
    tt.style.filter = 'alpha(opacity=0)';
    document.onmousemove = this.pos;
   }
   tt.style.display = 'block';
   c.innerHTML = v;
   tt.style.width = w ? w + 'px' : 'auto';
   if(!w && ie){
    t.style.display = 'none';
    b.style.display = 'none';
    tt.style.width = tt.offsetWidth;
    t.style.display = 'block';
    b.style.display = 'block';
   }
  if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
  h = parseInt(tt.offsetHeight) + top;
  clearInterval(tt.timer);
  tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  },
  pos:function(e){
   var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
   var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
   tt.style.top = (u - h) + 'px';
   tt.style.left = (l + left) + 'px';
  },
  fade:function(d){
   var a = alpha;
   if((a != endalpha && d == 1) || (a != 0 && d == -1)){
    var i = speed;
   if(endalpha - a < speed && d == 1){
    i = endalpha - a;
   }else if(alpha < speed && d == -1){
     i = a;
   }
   alpha = a + (i * d);
   tt.style.opacity = alpha * .01;
   tt.style.filter = 'alpha(opacity=' + alpha + ')';
  }else{
    clearInterval(tt.timer);
     if(d == -1){tt.style.display = 'none'}
  }
 },
 hide:function(){
  clearInterval(tt.timer);
   tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
  }
 };
}();

Now on to the CSS for the tooltip which is completely customizable to match any interface.

#tt {
 position:absolute;
 display:block;
 background:url(images/tt_left.gif) top left no-repeat;
 }
 #tttop {
 display:block;
 height:5px;
 margin-left:5px;
 background:url(images/tt_top.gif) top right no-repeat;
 overflow:hidden;
 }
 #ttcont {
 display:block;
 padding:2px 12px 3px 7px;
 margin-left:5px;
 background:#666;
 color:#fff;
 }
#ttbot {
display:block;
height:5px;
margin-left:5px;
background:url(images/tt_bottom.gif) top right no-repeat;
overflow:hidden;
}

To build and hide a tooltip call the script as below. The second parameter in the show function is optional, if not passed the width will automatically adjust to the content within the maxh limit.

onmouseover="tooltip.show('Testing  123 ', 200);"
onmouseout="tooltip.hide();"

If you run into any issues with this script or have any questions don’t hesitate to contact me at my blog’s contact form.

Categories: Webmaster Tools Tags: ,

KeyTable: Instant keyboard navigation in a table

March 18th, 2009 No comments

Allan Jardine is up to his old tricks again (his tricks are: creating helpful small tools!). This time he has created KeyTable, a library that adds the ability to use the keyboard to navigate around an HTML table.

Events can be bound (and unbound) to cells as required by the developer, allowing increased accessibility to Javascript enhanced tables. This library is somewhat similar to QFocuser that was posted on Ajaxian back at the start of the month, but specialises in table navigation. KeyTable also integrates nicely with DataTables, such that paging and sorting is taken into account.

To get started you just need to var keys = new KeyTable(); and then you can add init params for fine grained work, and you can also add events:

PLAIN TEXT

JAVASCRIPT:

  1. /* Example event listener */

  2. keys.event.focus( 1, 3, function() {

  3. /* processing on cell 1,3 … */

  4. } ); 

  5. /* this is exactly the same as */

  6. keys.event.focus( $(‘#example tbody tr:eq(3) td:eq(1)’)[0], function() {

  7. /* processing on cell 1,3 … */

  8. } );

The front page has an example that uses jEditable allowing you to mouse around, hit enter, change a field, and go back:

javascrip