Solving Cross Browser Issues - Part 3 (Mootools and HTML5)



Browser Chairs

In the previous two parts, I had a look at GWT, JQuery and Dart as possible solutions for solving cross-browser issues.

In this post I am going to have a look at Mootools using the same criteria as in the previous posts and have a look at a HTML5 solution.

Mootools



Note that when I created the main snippet for this post I made use of Mootools version 1.3.2 and was forced to manually add the paste event required by my criteria (you know the event thats not supported by Opera but by everyone else).

 
// Required by older Mootools versions
 
Object.append(Element.NativeEvents, {
  'paste': 2
});
 
Element.Events.paste = {
  base : 'paste',
  condition: function(e) {
 
	// More of an afterpaste event
 
	this.fireEvent('paste', e, 1);
    return false;
  }
};
 


This all changed however with the latest version (currently 1.4.4) in which you can exclude the preceding snippet - which obviously means that the paste event is now included by default.

In the following snippet you can see the Mootools version of the criteria:

 
window.addEvent('domready', function() {
	$$('textarea').each(function(sender)
	{
		var maxlength = sender.get('maxlength');
		if (maxlength != null)
		{
			sender.addEvent('keypress', function(e){
				if ((e.code == 8) || (e.code > 36) && (e.code < 41)) return true;				
					return sender.value.length < maxlength;
			});
 
			sender.addEvent('paste', function()
			{
				setTimeout(function(){
					if(sender.value.length > maxlength)
						sender.value = sender.value.substring(0, maxlength);}, 1);
			});
		}
	});	
});
 


Looking at the snippet above you'll probably notice a few similarities to JQuery; the two technologies do infact overlap in quite a number of ways. There is nonetheless a few fundamental difference between them but I am not going to go into too much detail, read about it over here.

Like previously mentioned I initially used an older version of Mootools which gave me a different take on the technology. I felt a bit irritated about having to do something dicey in order to attach something as simple as a paste event, the exact same thing I had to do when using the GWT.

I did however start to see wisdom in an approach of excluding cross-browser unsupported functionality in a framework like Mootools (not sure if this is really one of their aims seeing that the newer version now supports the excluded event).

A framework can provide us with a way to establish boundaries, the premise being that if we play within these boundaries we'll likely be safe. We can of course still allow developers to play outside these boundaries but at their own risk of writing code thats NOT going to be cross-browser friendly (sounds like GWT/JSNI scenario).

I don't believe that the creators of Mootools & JQuery set out to create any real boundaries as such (someone correct me if I am wrong).

It would of course be very difficult to create real boundaries seeing as nothing stops the developer from accessing the raw DOM (even by accident) and using something cross-browser unfriendly.

If you were using something like GWT its a completely different matter, since you don't have real access to the raw DOM (minus using the JSNI, but thats not something you'll use by accident)

HTML5



There is currently a lot of buzz in the air about HTML5 which boasts features like:
  • Offline storage.
  • Canvas library.
  • Audio/Video support.
  • New inline elements (e.g. mark, time, meter, progress)
  • New form types (datetime, date, month, week, time, number, range, email, url)

How will this affect cross-browser issues? Well, some suggests that HTML5 will greatly improve the situation. I am personally not too conviced, especially if we look at how shady current implementations are.

Incidently the aim of the criteria used in this series of posts is to add support for something thats actually part of the HTML5 specification, but currently only implemented by 3/5 browsers - we're already busy creating workarounds.

I do nevertheless believe in HTML5 and see it as a step in the right direction.

Also in all fairness I managed to find a HTML5 solution to fully implement the criteria in 5/5 browsers, observe the following Mootools snippet.

 
window.addEvent('domready', function() {
	$$('textarea').each(function(sender)
	{
		var maxlength = sender.get('maxlength');
		if (maxlength != null)
		{
			sender.addEvent('input', function()
			{
				if(sender.value.length > maxlength)
					sender.value = sender.value.substring(0, maxlength);
			});
		}
	});	
});
 


Instead of attaching handlers to the keypress & paste event, I've only attached a handler to the input event (one of the many new events available in HTML5).

I will have a deeper look into HTML5 is future posts.

In the next part I am going to have a look at Yahoo's YUI library.




Post/View comments
 

Solving Cross Browser Issues - Part 2 (GWT and Dart)



In the previous part of the post I had a look at combatting cross-browser issues using JQuery and gave a quick introduction to the GWT (Google Web Toolkit).

For those of you that came in late, cross-browser issues refers to the issues that arise due to the fact that the browser creators are inclined to implement the web standards differently.

In this post I am going to take the criteria used in the previous post and show you some source code examples of how to use GWT and Dart (bear in mind that Dart is unstable and still in its pre-infancy).


The GWT SDK is available over here and the Dart SDK over here.


GWT



I don't code in Java all that often and in addition this is the first time I've attempted using the GWT, but I found it (version 2.4) fairly straightforward to use, look at the following Java snippet:

 
package firstdemo.client;
 
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.*;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.ui.TextArea;
 
public class FirstDemo implements EntryPoint {
public void onModuleLoad() {
	NodeList<Element> textareas =  Document.get().getElementsByTagName("textarea");
 
	for(int i = 0; i < textareas.getLength(); i++)
	{	
		final TextArea textarea = TextArea.wrap(textareas.getItem(i));
		final String maxlength = textarea.getElement().getAttribute("maxlength");
 
		if (!maxlength.isEmpty())
		{
			textarea.addKeyPressHandler(new KeyPressHandler()
			{
				public void onKeyPress(KeyPressEvent event)
				{							
					int keyCode = event.getNativeEvent().getKeyCode();
					if (((keyCode == KeyCodes.KEY_BACKSPACE) || (keyCode >= KeyCodes.KEY_LEFT)  && (keyCode <= KeyCodes.KEY_DOWN))
							|| (textarea.getText().length() < Integer.parseInt(maxlength))) return;		
					event.preventDefault();
				}
			});
			addPasteHandler(textareas.getItem(i), maxlength);
		}
	}	
}
 
	public native void addPasteHandler(Element element, String maxlength)
    /*-{
        element.onpaste = function(e) {
			setTimeout(function()
			{
				if(element.value.length > maxlength) {
					element.value = element.value.substring(0, maxlength);
				}							
			}, 1);
 
        }
    }-*/;	
}
 


Like previously we iterate through all the textareas on the page and attach event handlers wherever we find the maxlength attribute.

Now Google states that "GWT shields you from worrying too much about cross-browser incompatibilities. If you stick to built-in widgets and composites, your applications will work similarly on the most recent versions of Internet Explorer, Firefox, and Safari. (Opera, too, most of the time.)"

Unfortunately I couldn't stick to the built-in composites since the required paste event is excluded from the GWT, likely because its not completely supported by all browsers, which forced me to make use of the JSNI (see addPasteHandler method).

Thanks to the JSNI I was able to add my browser specific code, but also add code that won't work in all browsers - the paste event wont be fired by Opera for example.

Which makes me inclined to go as far as to say that you must steer clear of the JSNI if you're interested in writing cross-browser friendly code.

All in all it does however feel like a helluva lot of extra code to write if you compare it to something like JQuery, but I nevertheless started liking GWT over the last few weeks.

Dart



If you're unfamiliar with Dart, its basically a new language that Google is busy developing for the web, very similar to JavaScript - I think of it as JavaScript on steroids (or the next step in evolution of JavaScript).

But just like GWT (currently at least) it compiles to JavaScript and in fact many of the developers that worked on GWT are busy working on Dart.

At the moment its not much of a cross-browser solution as it only supports three of the big five (Chrome, Safari 5+, Firefox 4+), but like mentioned previously its a technology thats in its pre-infancy (don't use it in a production environment).

Lets have a look at some code:

 
#import('dart:dom');
 
void LimitTextAreas()
{
  NodeList nodes = window.document.getElementsByTagName("textarea");  
  for (int i = 0; i < nodes.length;i++)
    {
      HTMLTextAreaElement obj = nodes[i];
      Node node = obj.attributes.getNamedItem("maxlength");
      if (node != null)
      {
        int maxlength = Math.parseInt(node.nodeValue);
        obj.addEventListener("keypress", (KeyboardEvent e) {
          if (((e.keyCode == 8) || (e.keyCode > 36) && (e.keyCode < 41)) 
              || (obj.value.length < maxlength)) return;        
            e.preventDefault();
        });
        obj.addEventListener("paste", (Event e){      
          window.setTimeout((){        
            if(obj.value.length > maxlength)
              obj.value = obj.value.substring(0, maxlength);
          }, 1);
        });
      }
    }
}
 
void main() {
  LimitTextAreas();
}
 


Looks familiar and JavaScripty right? Well, a lot of parts also feel a lot like Java/C#, you can even create proper classes etc. But hang on, is it statically typed, why did I define all the types?

No, its actually a dynamically typed language just like JavaScript, so you'll be able to replace NodeList, int, HTMLTextAreaElement etc all with the var keyword.

Statically typing your variables are completely optional, but I prefer doing it since it might help me in catching errors earlier etc, you can read more about it over here.

Otherwise it seems like a very simple/easy language to learn.

Its going to be interesting to see if/how the programming community embraces this new language within the next few years.

Concerns



But hey, wait a minute, these technologies seem awfully similar, dont they? It actually led me to ask the following question to one of the google devs I met recently:

Hi Mike

Just a quick question (if you dont mind)

How committed do you believe Google is to its GWT project ?

I am asking this in context of the following two things.

  1. its parent project only having a 15 month lifespan, from public release to being annouced discontinued.

  2. The dart project - which feels like a like minded project?


I didn't get a response from Mike, but I found a post on the official GWT blog where someone answers this question.

The GWT team is basically saying that they see Dart as an evolution of GWT's mission (evolution generally entails the extinction of the less evolved species), but don't worry guys we're (Google) using GWT as well, so we're not planning to kill it off too soon.

Here is a full discussion on the subject.

You can also download the source code for this post over here.

In the next part we're going to have a look at Mootools.




Post/View comments
 
First 1 2 3 4 5 6 7 8 9 10 Last / 65 Pages (130 Entries)

Latest Posts

MS SQL: Parameter Sniffing


2012-05-21 22:38:48

Be the best stalker you can be


2011-12-13 22:33:54

Top 5 posts

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21