February 12, 2008

Placing JavaScript correctly

You will find other articles relevant to this document in these sections:
Richard Lee @ 5:24 pm

How often do you visit websites with script errors? Frequently my Firebug Firefox Add-On lights up with “undefined” errors when I visit JavaScript intensive websites. Sure it doesn’t affect the functionality of the site (usually) but it’s just plain bad form, specially when it’s so easily avoided. Where you place your JavaScript should depend on how it is used in your site - Here’s some simple rules of thumb for placing JavScripts:

If the script needs to be run before the page is fully loaded to do some pre-processing for example such as browser and
resolution checks place the script in the header as this is always loaded before content in the body:

<head>
 
<style type="text/css" media="all">
@import "css/layout.css"
</style>
<script language='text/javascript'>
<!--
/*
For the purpose of example this script would load a stylesheet
based on the screen resolution.
*/
 
var width = screen.width;
var height = screen.height;
if (width < 1024) {
 document.write('<style type="text/css" media="all">@import "css/layout800×600.css"');
} else {
 document.write('<style type="text/css" media="all">@import "css/layout1024×768.css"</style>');
}
// -->
</script>
</head>

If the script manipulates html content the DOM must exist prior to the script execution. To make sure this is the case you can use the native window.onload() method which fires when the total document is loaded:

<head>
<script language='text/javascript'>
<!--
/*
For the purpose of example this script would create
a menu for the site
*/
 
function init_menu() {
 
   // do stuff here
 
}
window.onload = init_menu();
//-->
</script></head>

Or placing you could place your script /function call later in the document - usually just before the closing body tag:

 
<script language='text/javascript'>
<!--
init_menu();
// -->
</script>

I typically use the latter (before the closing body tag) because you can simply call multiple scripts relatively safely and avoid any window.onload() clashes since it is very possible other third-party scripts may be using this.

Update:

In addition to the above methods to make sure the DOM is loaded you can use the Prototype libraries “DOM ready”, dom:loaded event observer (which I have been using more recently) since it fires once the page markup has completed but before all the images etc have loaded:

document.observe('dom:loaded', function(){
 //any code here will be read once the DOM is ready, before images are loaded etc
});

And lastly, it’s always a good idea to check the DOM element(s) your targeting exist before you start manipulating them:

<script language='text/javascript'>
<!--
 
var glider = document.getElementById('glider');
if (glider != undefined) {
   // do stuff
 
}
// -->
</script>

September 25, 2006

Addressing the IE Flash/Embed Issue

You will find other articles relevant to this document in these sections:
Richard Lee @ 10:45 pm

If you recall the Eloas lawsuit filed against Microsoft for infringing on its patented browser technology you’ll remember Microsoft was forced to change how IE handled embedded programs within webpages. So, over the past 2 years Microsoft has been fiddling with the way handles embedded media within web pages. Early last year MS released the SP2 update, which saw the biggest changes to IE. A part from a much needed Popup Blocker,MS introduced very obtrusive ActiveX Prompt which detected embedded content and prevented pages from fully loading until the user confirmed the prompt. More recently Microsoft introduced a ‘click to active’ mechanism to IE. You may not have experienced this first hand if your a Firefox user or your lucky enough to frequent sites with workarounds in place. But essentially in order to activate embedded content such as Flash, IE requires that you actually click the movie. This is most annoying for interactivity within Flash movies when you consider it would take 2 clicks to invoke a getURL() action; on(release){ getURL('http://www.mysite.com.au', '_blank'); }. Fortunately Microsoft still lets us use JavaScript to Embed our Flash movies, and cool guys such as Geoof Stearns have already done the hard work for us - The SWFObject JavaScript. Developed by Geoff Stearns the SWFObject script is actually used by Microsoft and Adobe and it’s ridiculously easy to use. Just a simple inclusion and a small amount of JavaScript and your done:

<div id="flashPlayer"><!-- Flash content will go here //--></div>
<script type="text/javascript">
var so = new SWFObject("swf/movie.swf", "mymovie", "200", "100%", "7", "#336699");
so.addParam("quality", "low");
so.addParam("wmode", "transparent");
so.addParam("salign", "t");
so.addVariable("mp3File", "mp3/numb.mp3");
so.write("flashPlayer");
</script>

Here’s a quick rundown of the script;

Create the HTML element which will contain the final Flash content(I’ve used a div):


<div id="flashPlayer"><!-- Flash content will go here //--></div>

Create a new SWFObject, pass it the path to the swf file, movie name, width, height and Player version we want to detect for followed by the background colour:

var so = new SWFObject("movie.swf", "mymovie", "200", "100%", "7", "#336699");

Add the usual parameters using the addParam(param name, value); function:

so.addParam("qality","low");

Pass as many variables as you want to Flash with the addVariable(variable name, value); function:
so.addVariable("mp3File", "mp3/numb.mp3");

Finally write the Flash content to the HTMLcontainer you created above (the div):

so.write("flashPlayer");

More Information;

SWFObject documentation (deconcept.com)

ActiveX changes in Internet Explorer (MSDN)

There are also extensions available to integrate IE workarounds, I haven’t tested these myself though
Dreamweaver MX 2004/8 Extensions;

Softery IE Flash Problem Solver by Softery (on Adobe Exchange) (FREE)

CMX Insert FlashObject 1.2 by Paul Newman (on Community MX)

GoLive 5.x Extensions;

JM SWFObject Action by Jesper Moller (on Adobe Exchange) (FREE)

August 9, 2006

Basic AJAX with XMLHttpRequest Class

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 12:02 pm

There is a lot of buzz going around RIA and Web2.0 these days, and at the heart for HTML this involves AJAX. We use AJAX as a way to make a request via JavaScript and return a response from the server, which can be Text or XML.

The fundamental object we use in AJAX to perform this functionality is the XMLHttpRequest class. This class allows us to create a HTTP request and receive a response from the server. The object as itself is quite basic, and allows you to inject in header variables, such as POST vars, and return back a string or XML (DOM Compliant object) response.

I thought I would quickly provide a quick outline of making a request using this object, that I can build examples off in the future, and hopefully discuss a JavaScript framework I wrote around it to handle calls and relaying the responses to appropriate functions.

Creating XMLHttpRequest Objects

There are a few different way for us to create an XMLHttpRequest object, between IE and Mozilla style browsers. The most effective way to create a XMLHttpRequest would be to create a factory method that returns our XMLHttpRequest object depending on the browsers support. Our method would return NULL if our browser isn’t capable of performing the functionality.

function createXMLHttpRequest() {
  if(window.XMLHttpRequest) {
    try { 
      xmlHttpRequest = new XMLHttpRequest();
    } catch(e) { return null; }
  } else if(window.ActiveXObject) {
    try {
      xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) { return null; }
    }
  } else return null;
  return xmlHttpRequest;
}
 

Creating a request

We can now create XMLHttpRequests and instruct them how to perform. Here is an example to make a request using our XMLHttpRequest object:

  xmlHttpRequest = createXMLHttpRequest();
  if( xmlHttpRequest  == null) alert("No XMLHttpRequest available");

  // Make the call
  xmlHttpRequest.open("GET", "http://localhost/myscript/?do=whatever", true);
 
  // Associate the ready state change
  xmlHttpRequest.onreadystatechange = function() { alert("We have a changed state!"); }

  try {
    // Send the Method Data
    xmlHttpRequest.send(null);
  } catch(e) { alert("Send  failed"); }
 

When we create the XMLHttpRequest object and use the send() function we need to specify a “onreadstatechange� function that gets called when the XMLHttpRequest object changes state.

The XMLHttpRequest object has several different properties we can access to retrieve our response.

readyState - Object Status INT

responseText - Response as a String

responseXML - DOM Compatible document object from response

status - HTTP Response Codes (200, 404 etc)

statusText - HTTP Response Code Text

Throughout a request lifecycle of the XMLHttpRequest object, it rotates through the following states:

0: “uninitialized”
1: “loading”
2: “loaded”
3: “interactive”
4: “complete”

We can access the response once the state of the XMLHttpRequest object has reached state “4�.

Changing our above example, we can incorporate the XMLHttpRequest properties to determine our result:

xmlHttpRequest.onreadystatechange = function() { 
  try {
    if(xmlHttpRequest.readyState == 4) {
      if(xmlHttpRequest .status == 200) {
        // We have a successful HTTP request with data
        alert("we received:" + xmlHttpRequest.responseText);
      } else {
        // We have an error
        alert("our call failed:" + xmlHttpRequest.status + " " + xmlHttpRequest.statusText);
      }
    }
  } catch(e) { alert("Unable to determine the state of the call");
}

Security

It is also worth noting that due to JavaScript sandboxing issues, it is necessary to:

a) Check from a HTTP: protocol, not a FILE:

b) Only access the information from the same domain, don’t make a call to a different domain.

Where to from here?

Overall this gives us a very basic framework that we can wrapper and write our own functions around. We can extend the base xmlHttpRequest object to handle functionality such as implementing

  • Event Listeners

  • Timeouts/Abort

In the near future I will post an article with an example of making a request and handling a response.

July 31, 2006

My AJAX Framework

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 12:13 pm

I have setup both a PHP and JavaScript framework for making fast AJAX calls. There are a number of implementations of AJAX frameworks out there, but I have found it better to create my own specific server and client implementation so I can implement AJAX patterns in my own versioned controlled project. This will allow me a greater flexibility and ability to extend from my own code.

The idea around the implementation was to be a purely service level framework. A lot of the other frameworks that are available provide quite a bit of dependency between the server and the javascript (often trying to help you generating your JavaScript - which is nice, but also limits you as you could simply change the gateway server implementation from one language to the other, and often influences your design of both the server and the client). Being a service level framework it does not provide the other extended JavaScript functionality that other frameworks offer, such as Drag and Drop helpers, Autocomplete boxes and the like. These can be implemented ontop of the service level framework as seperate libraries, with hopefully close to no reliance on the service framework.
I have modelled the PHP off a MVC/Model 2 implementation that has a build up/tear down of ~5ms (before optimisations, such as concat single file, or compile to bytecode) to service a request and build a response. The design of the framework allows the response to be changed in a modular fashion, such as building a JSON response. The actions are seperated out to promote reusability and modularity and we have an action server and request processor to handle the application process, authentication and application configuration. It will allow the RPC/Request to be processed quickly through a reusable framework.

On the Javascript client end I have built a RPC/Remoting style framework. The framework handles the creating of the request to be sent to the server and allows API to manage state and response. This allows Requests/Calls to be handled individually through a service with state observers and relay responders, and implements timeouts and fault handling.
I am still considering how I will proceed with the framework, I am waiting for a project where I can really take advantage of it.

July 28, 2006

Creating accessible Popup windows

You will find other articles relevant to this document in these sections:
Richard Lee @ 3:09 pm

Often when we create complex pages with lots of content it’s advantageous to use popups for smalls bits of information such a “Help” text. However since the introduction of popup blockers this once simple task has proven to be a tedious job. For example, by default the IE 6 Popup Blocker will block active scripting opening windows without user clicks i.e. using onload() in the body tag for instance. Higher security settings in IE will even prevent scripted popups running off user clicks. So what’s the answer? I came up with a few ideas, my initial thought was to try and detect if my window would be blocked. To do this I would check whether window.open returned a reference to an object:

function popUpWin(url, width, height) {
 
if (window.open) {
window.open(...);
} else {
alert('It appears your browser is blocking popup windows');
}
}


<a href="javascript:popUpWin(disclaimer.htm, 450, 500)">Read Disclaimer</a>

Although sites use this today it’s not a viable solution because it primarily validates the browser and ultimate won’t provide the user with a working link. Instead the user is expected to go off and adjust their browser settings and re-launch the window. Worse still they might potentially miss important information you were trying to provide in that popup (i.e. a disclaimer).
My next more user-orientated solution is what I use today. Employing the JavaScript onclick() function we can call our popUpWin() funcion, and at the same time we can still use our href attribute to supply a normal link if the javascript fails:

function popUpWin(url, width, height) {
 
if (window.open) {
window.open(...);
}
}

<a href="disclaimer.htm" onclick="popUpWin(this.href, 450, 500);return false;" >Read Disclaimer</a>

July 12, 2006

Word Wrapping in IE and Firefox

You will find other articles relevant to this document in these sections:
Richard Lee @ 6:15 pm

It’s a bit of a nightmare really. When a word is longer than its containing block-level element it tends to break out. Fortunately in IE 5.5 and above there’s the word-wrap:break-word porperty which can be used to break words longer than their respective containers.
Here’s an example using IE conditional comments:

 
<!--[if IE gt 5.0]
<style type="text/css">
.content{word-wrap:break-word;}
</style>
<![endif]-->
 

However there is no such property that will work in Firefox. So what to do? After a bit of head scratching I decided to have a look at using JavaScript. Although I am yet to come up with my own solution here it is in Spanish thanks to Mr El Micox :)

June 19, 2006

AJAX Drilldown Menu

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 3:57 pm

Last year I worked on a website called Living Edge which sell classic furniture by great designers (such as Ray and Charles Eames, Charles Wilson, Norman and Quaine, George Nelson, Bill Stumpf) and brands (Herman Miller, Emeco, Walter Knoll and the like).

The project was based off a custom written content management database that allowed the Living Edge staff to maintain every aspect of their online product catalog online, such as creating designers, manfacturers, categories, products, galleries and work with PDF and CAD attachments to create a rich useful interface to their A’n'd (architects and designers).

As a core requirement to the project we had to consider an implementation of a search engine which would allow architects and designers to choose their preferred way of browsing a catalog (such as via their favourite designer or brand, or look under particular categories to find inspiration). With this in mind and with LivingEdge providing such a comprehensive product catalog, I implemented a series of AJAX based Drilldown Menus.

The AJAX technology was fairly new to me at the time, but was fastly becomming respected as the direction for creating powerful HTML interfaces. I chose AJAX because we could quickly drill down through the product catalog without requiring refreshes or mass data to be sent to the clients browser. It also was a way for us to limit the possibility of users choosing combinations that did not exist and result in “zero” matches.

Overall we were able to provide real-time indications of how many results would be returned for each combination and indicate beside each option. We could also remove options and guide the user quite quickly. Users could start anywhere across the dropdowns and only place in as much information as they like.

I implemented the solution using PHP to query my relational database, and built XML WDDX packets to translate the information (in a datastructure) to the front-end clients JavaScript API. I used a simple framework called SAJAX as a basis for handling my HTTP XML Requests. I also created a server-side proxy which would instantly return packets based on the criteria parsed to the server through the request to dramatically reduce load and execution times of queries. Overall it was very very snappy.

The client was very happy with how the search engine worked, and has sparked a “revamp” of several of its competitor websites. LivingEdge were able to raise the bar and provide a very quick and useful resource for their visitors to use.

Visit the Living-Edge site here.
(Interface Design, Flash and Graphics by Sacha Jerrems)

You can learn more about AJAX and AJAX design patterns online by checking out the very useful resource: http://www.ajaxpatterns.org/ or view information about SAJAX here. You can learn about distributed data exchanges on WDDX here.

June 17, 2006

Creating internal popup windows or notes with CSS/JavaScript

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 6:08 pm

Often you need to create some way to display a message over the top of the current screen. This can be things like disclaimers or popup windows with ads in them etc. Instead of running into problems with using JavaScript window.open() events and Popup blockers you can use simple JavaScript and CSS properties to create an internal popup window or note infront of your HTML.

The possible uses of this are:

- Dynamic Notes or Messages, such as better presentation of Error Messages from Form Validation
- Popup Disclaimer over content that are hidden once the user hits “I agree”
- Displaying promotional material, such as a Flash advertisement

Typically using DHTML we are using JavaScript to change the properties of elements of a webpage. Each element appearing on a website has certain values which we can change dynamically based on events such as an onclick or hitting submit on a form.

Simple panel window over HTML content

The simplest example of a internal “popup” window that sits above the text. To do this we take advantage of the HTML element DIV. This element is a block-level element that by default does not contain any presentation attributes, like border, padding, margin or background. DIV’s have been widely accepted as the element to use when creating your HTML layout because of their flexibility and compliance with Content/Design seperation.

To create our simplest popup window we will apply some CSS-styles to the DIV element.

Z-Index (view w3c reference)
Z-Index terms to the layering of content. By default your HTML contents are placed at position 0. Imagine this as glass panes you look through on your computer screen. By assigning a element a Z-Index of 1 it creates another pane ontop of the original and it will sit cleanly over the elements at position 0.

Position (view w3c reference)
Position allows you to manage the location of where to place your popup window. You can use different attribute values like relative, absolute etc that allow you to position a DIV on your screen.

Visibility (view w3c reference)
The visibility property allows us to hide or display your HTML elements, in this case the DIV.

The CSS styles can be assigned into two classes that represent the states of your DIV; visible and hidden. Your DIV can then switch states by switching which style class is applied. We can do this by locating the element in the HTML document through the DOM (Document-Object-Model). To locate the object easiest we apply a unique ID to the DIV element (view w3c reference - Element identifiers: the id and class selector) and we can then use JavaScript to update the DIV elements class to represent its state.

Controlling a elements CSS property in JavaScript:

object = document.getElementById(’elementId’);
The JavaScript method ‘getElementById’ allows us to locate an element and gain a reference to it. Once we have a reference to this element we can access the properties of that attribute.

object.className = “cssClass”;
The property ‘className’ refers to the current classes applied to the element. It will start off containing the contents of the elements ‘class’ attribute. We can update this property to the name of the CSS class that represents the state of our DIV (eg. visible and hidden).

Popup Notification Window

An alternative method to displaying messages from JavaScript would be to mix what we have learnt with controlling CSS states with JavaScript and introducing dynamic creation of the DIV contents. This way when we wish to display the a notification or alert, we can generate the HTML contents into a DIV and then switch the CSS property to represent its value.

Making use of the following JavaScript functions are useful in achieving popup notifications:

object.innerHTML = “Hello World”;
This allows us a fast way to quickly create HTML content into an element (instead of creating new objects and attaching VIA the DOM model - this method is faster as tested here). Once we locate our element (using getElementById) we can then change the contents by applying it to the innerHTML property of the object.

We could then create our own version of the javascript:alert(msg) function to display a nicely formatted popup notification.

function notifyMsg(id,msg) {
// Locate and update our popup window
object = document.getElementById(id);
object.innerHTML = msg; // We could also create some HTML to prepend our message
// Add our additional options such as OK
object.innerHTML += ‘whatever such as a close button who uses javascript to switch the state of this element to hidden’;
// Change the CSS state to visible
object.className = ‘visibleNotifyMsg’;
}

Usability of the Window

We have to consider certain affordance with the popup window, to ensure that the window is dealt with smoothly and intiuitively without causing a great hick-up to the user. Using a “X - Close” in the top right handle of your window will help create a quick way for people to close the message. Also a button at the bottom or image saying Close Window may prove useful as well.

You will also need to ensure that there is enough contrast created through the use of Borders or Background Colour that helps differentiate it from the content it is sitting upon. A white popup window with black text sitting over white background with black text will loose your user. If there is some sort of action required, consider the use of Colours to help your user identify the action required, eg. If poping up a Validation Alert, consider using Red Text or a Red Cross icon at the top of your message.

Click here to view the HTML Example file

June 15, 2006

JavaScript Form Validation

You will find other articles relevant to this document in these sections:
Richard Lee @ 11:35 am

JavaScript provides us with a simple solution for form validation. Being completely client-side means that we can validate user data before we even make a request to the server, saving unnecessary load on the server. We can also prompt the user with dialogs in the form of alert and confirmation boxes. JavaScript isn’t without its disadvantages though. The biggest issue with JavaScript is that end-users must have active-scripting (JavaScript) enabled in their browsers. While a majority of browsers are JavaScript enabled by default, IE 6 Service Pack 2 users and those with 3rd Party Script blockers in Firefox will be alerted, and as a result paranoid users may choose to disable active-scripting on your web page.

Let’s take a look at a simple example of some JavaScript validation:





Line by line…


In the form creation we use the JavaScript onsubmit() function, which fires when a form element receives a request to submit. In this case I have used it to call my form validation function validate(), passing a relative reference to the form. Note the

return

statement. This is used to return the result of our validation to decide whether we send the request or not (i.e. a value of false will abort the request).


function validate(form) {

Since we passed a relative reference we can now reference all our form values via

form.<field>.value</field>

. Alternatively you could always store a reference to the form in a local variable, but passing but reference makes much more sense.


errStack = new Array();

Here I create an array to store my error messages. You can always concatenate a string of error messages and use a boolean variable to flag errors, however using an array means we can store a message, and then later check the length of this array to see if we have any error messages.


if (form.first_name.value == “”) {
errStack.push(”Please enter your first name”);

}

As mentioned above passing the relative reference to the form means we can now reference form elements using the relative reference of

form.field.value

. Here I check the value of the first_name field is not empty. If the value is empty I then “push” and error message into my errors stack errStack.


if (errStack.length > 0) {
alert(errStack.join(”\n”));

return false;
}

Following our field checks we have a final if() statement to check the length of our errors stack errStack. If the stack is longer than zero we have error messages that need to be reported to the screen. To do this we join all our error messages, delimited by the \n escape character so that each message is printed on a newline within the alert() box. Finally we return

false

which in turn aborts the form request.


return true;
}

On the other hand if the form passes all our checks we return

true

That was easy wasn’t it?

By no means is this the only way to validate a form using JavaScript but hopefully it provides you with an idea. For more references to JavaScript, and JavaScript validation I recommend visiting the W3Schools website.

 

June 9, 2006

IE FIX - Click to activate this control

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 2:43 pm

For Webdevelopers

Simple quick fix for an issue aftecting webdevelopers after Microsoft lost a legal battle over embedding active-x elements.

This is affecting embedded Active-X elements such as Flash/QuickTime/RealPlayer/Java Applets/PDF’s.

Under IE a message appears “click to activate and use this control“.

A fix for this a recommendation has been made to use the following snippet of JavaScript:

<script type="text/javascript" language="JavaScript">
// Obtain a list of all the "objects"
var documentObjects = document.getElementsByTagName("object");
// Loop throught the items and reassign the outerHTML
for(var x = 0; x < documentObjects.length; x++) documentObjects[x].outerHTML = documentObjects[i].outerHTML;
</script>

This code needs to be copied into your section of your HTML page. As this relies on JavaScript your users will have to have it enabled. Typically this only affects around 10% of browsers (according to W3C as of January 2006).

You can create a file called “IEActiveXFix.js” and copy the contents between the script tags into the file. You can then “include” this with the following at any stage:

<script language="JavaScript" type="text/javascript" src="IEActiveXFix.js"></script>

You could also make use of the following conditional include:

<!--[if lte IE 7]>
<script language="JavaScript" type="text/javascript" src="IEActiveXFix.js"></script>
<![endif]-->

For end-users

Visit http://support.microsoft.com/default.aspx/kb/917425 to download a patch.

Next Page »