Solving Cross Browser Issues - Part 1 (JQuery and GWT)



When writing JavaScript I generally try to cater for the big 5 (IE, Firefox, Chrome, Opera and Safari), an endevour that gave me a lot of grey hair last week while sorting out issues that I noticed on a few of my older projects (created before the advent of Chrome).

I would adapt a script to work for Chrome which would cause it to break in FireFox, when I fixed it for FireFox it would break in Safari, which in turn ends up breaking IE (no surprises here), eventually I managed to make all the browsers happy (on a stack of cards), at the expense of a lot of precious time.

This is obviously a bit ridiculous and emphasizes the need to use some kind of abstraction/framework that provides common ground to all of these browsers, an issue that I believe greatly contributed to the birth of technologies like GWT (Google Web Toolkit) and JQuery.

In this post I am going to have a quick look at the technologies mentioned in the preceding paragraph, bear in mind I am no expert on any of them (been creating scripts using JQuery on/off over the last few years, my GWT knowledge is solely theoretical at the moment).

Feel free to comment on other sane solutions that you've used.

Note that I am going to use the following raw JavaScript snippet as my criteria to demo and compare solutions throughout this series of posts:

 
function limiter()
{
	var textareas = document.getElementsByTagName('textarea');
 
	for(var i = 0; i < textareas.length; i++)
	{
		var textarea = textareas.item(i);
		limit(textarea);
	}
}
 
function limit(sender)
{
	var maxlength = sender.getAttribute('maxlength');
	if (maxlength != null)
	{
		// limit input values
		sender.onkeypress = function(e)
		{					
			// Crossbrowser Issue 
			if (e == null)
				e = window.event;
 
			// exclude certain keys from our limiter
			if ((e.keyCode == 8) || 
				(e.keyCode > 36) && 
				(e.keyCode < 41)) return true;
 
			return (sender.value.length < maxlength);
		}
 
		// limit pasted values
		sender.onpaste = function()
		{
			// onAfterPaste
			setTimeout(function()
			{
				if(sender.value.length > maxlength) {
					sender.value = sender.value.substring(0, maxlength);
				}							
			}, 1);
		}
	}
}
 
// Only Attach events needed for limiting the textareas once the page finished loading
if (window.addEventListener) { // FF etc
	window.addEventListener('load', limiter, false);
}
else{ // IE
	window.attachEvent('onload', limiter);
}
 


Few things to note about the preceding snippet:

  • Its intention is to add support for the maxlength attribute to textareas, note that this is something that is part of the HTML5 specification and currently only supported by 3/5 of the big browsers.

  • It tries to be cross-browser friendly, but fails - the use of the paste event not supported by Opera and the keyCode property being used on the event object.

  • The use of all kinds of horrible browser specific code, like how to retrieve the event and the way we attach events in different browsers.


Lets have a look at how to improve this script.

JQuery



To be honest the first time I saw JQuery I didn't really pay too much attention to it, mainly because it wasn't the only JavaScript library around.

But as soon as Microsoft employed guys like Rey Bango and started shipping JQuery with Visual Studio not to mention providing JQuery (along with Google) via their CDN networks, I started taking it seriously.

In the following snippet you can clearly see the advantages of using JQuery (over the raw script).

 
$(function() {
	$('textarea[maxlength]').each(function(index, element)
	{
		var maxlength = $(this).attr('maxlength');
		$(this).bind('keypress', function(e) {
			if ((e.which == 8) || (e.which > 36) && (e.which < 41)) return true;				
			return (element.value.length < maxlength);
		});
		$(this).bind('paste', function(){
			setTimeout(function()
			{
				if(element.value.length > maxlength)
					element.value = element.value.substring(0, maxlength);
			}, 1);
		});
	});
});
 


What we're seeing at the top is a lot less code, a lot cleaner code and cross-browser friendly at the same time.

I must point out however that by merely using JQuery you're not magically going to be immune against all cross-browser issues, time and time again I've come across JQuery plugins (written by third parties especially) that are not cross-browser friendly.

Regardless of using JQuery we can still get our hands dirty, even looking at the simple JQuery example in the preceding snippet you might notice thats its still not completely cross-browser friendly. I am of course referring to the use of the paste event thats not supported by all browsers (not to mention the ugly setTimeout hack being used).

GWT (Google Web Toolkit)



GWT (byproduct of the Google Wave project) involves tools (GWT Compiler, Eclipse plugins etc) provided/used by Google to write rich browser based applications using Java, which gets translated into the appropriate JavaScript (cross browser friendly and apparently highspeed/optimized).

Now recently I went to my first google event where Mike Springer talked about GWT (among other things).

The audience didnt ask a lot of questions, but I am going to share two of the questions asked and paraphrased approximations of what Mike replied (in grey) and some thoughts I've got on the matter.

Christoff Truter at gsouthafrica event
(from left to right, Wayne, Jason aka dum dum, Cornell and me)

  1. Can we use GWT with other languages like PHP for example?

    Yes, since GWT compiles into JavaScript you must only really be concerned about handling the AJAX read/write from and to GWT, something you can handle with JavaScript overlay types - introduced in version 1.5 of GWT.

    Ideally I feel that if I am going to use GWT it would make more sense sticking with Java all together (omit PHP etc) where possible because:

    • Java is its native platform, which generally means better support and tools.

    • I like the idea of only using one programming language (if we exclude HTML & CSS as being languages and substitute JavaScript with Java), else it would mean that you'll likely be adding a third programming language (Java) to your website, assuming that human written JavaScript remains part of the equation.

      Which obviously adds an unnecessary level of complexity, maintenance and skills needed.


  2. Can we use GWT with JavaScript libraries like JQuery?

    Yes, you will able to integrate with any JavaScript library using the JavaScript Native Interface (JSNI) of GWT.

    I don't like mixing technologies too much (kinda like mixing your booze), especially technologies with the same goals in mind.

    Unfortunately we don't always have a choice in the matter, especially when working with legacy code or if doing so would save us some precious time (debatable in the bigger picture).

    I once had to work on a project where almost every developer that worked on it before introduced his own preferred javascript library (even though all the libraries did the same thing at the end of the day). I would hate to be the guy that introduces even another partner to that polygamous relationship.

    So personally if I ever plan to use GWT, I will do so on new projects (or projects void of existing like minded tech) and on old projects try my best to make the existing technology work.


In the next part of this post I am going to move a little bit out of my theoretical knowledge of GWT and attempt to write a GWT version of the criteria used in this post, which should give us a fairly basic code comparison.

I am also going to have a look at Google's new language for the web - Dart.




Post/View comments
 

Be the best stalker you can be



I recently retired from an illustrious career in stalking and decided today that I need to pass down my incredible knowledge to aspiring stalkers.

I know it's a bit of a cliché but you're never too young or old to become a stalker.

The following list contains some crucial information you need to know if you want an impeccable career like I had.

  1. Stalkers Anthem

    The first thing that you need to know as stalker is of cource the stalkers anthem, but what is the importance of an anthem?

    Well, think about the scene in Rocky 1 where Sylvester Stallone runs up the stairs with eye of the tiger playing in the background, its all about being inspired, being proud of who you are and what you're about to do.

    So every day before you go out to stalk your stalkee, remember to play the stalkers anthem "Every Breath You Take", thank you Sting - You're an inspiration to all of us!

    Every breath you take
    Every move you make
    Every bond you break
    Every step you take
    I'll be watching you

    Every single day
    Every word you say
    Every game you play
    Every night you stay
    I'll be watching you

    Oh can't you see
    You belong to me
    How my poor heart aches
    With every step you take








  2. Build a shrine



    Building a shrine in honour of your stalkee is quite important, I am sure you're familiar with the phrase "keep your eyes on the prize" - at the end of the day thats what its all about.

    One crucial component to your shrine is of course the use of photos, you need to have as many photos as humanly possible of your stalkee, it would also be highly advisable to pin these photos against a wall, preferably a wall thats not too visible to everyone, e.g. inside a cupboard wall - because you dont want anyone to think you're creepy or anything.

    Also avoid the use of candles in your shrine, you're a stalker not a serial killer! (you also dont want to burn down your cupboard in the process)

  3. Equipment



    Ever wonder what bird watching equipment is really for?

    No stalker can truly be successful without a good pair of binoculars, get yourself the strongest pair money can buy, acquire a really big telescope if that's not good enough. (bird watching is a good cover story though)

    Night vision is also a must have, your stalkee must go to bed eventually like everyone else?

    Also get yourself a strong listening device and become skilled at lock picking in order to plant audio surveillance equipment in their phones, cars etc.

    While on the subject of breaking an entering, why not hide a few high resolution cameras in some discreet areas of their habitat and remember to leave a red rose on their pillow every night before they go to bed.

  4. Social Networking

    The advent of social networking really made stalking a lot easier, facebook, google plus, twitter just to name a few.

    I found that twitter is only second to google plus when it comes to being stalker friendly, while facebook makes it a little bit harder, but with some creative swindling it might become your most powerful stalking ally.

    Now the key to using social networking as a stalking tool is of course the use of aliases, you will most definitely need to create multiple aliases - doing so will make it less suspicious.

    You might ask me how many aliases do you need to be effective, is there some kind of formula I can use?

    Well, I found after doing years of research that there is in fact a relation between your followers on twitter, facebook and google plus and the number of aliases you need, simply multiply by two.

  5. Clothing



    Avoid wearing clothing that would draw too much attention to yourself; as stalker you must be stealth minded towards everything wardrobe related.

    Night times you're ordinarily going to spend most of your time in obscurity up in trees and behind bushes, so make sure that you've got a lot of black clothing in your cupboard (also useful for hiding your shrine).

  6. Join the CIA



    Chances are fairly good that your stalkee will be surrounded by friends, family, a spouse or someone, now in the event of them noticing you, you might need to defend yourself physically (or legally).

    So I would definitely recommended that you go for self-defence classes, a quick solution would be to simply join the CIA - you'll get all the training you need to be an effective stalker plus a good cover story. You would also save a lot of money on equipment etc.

  7. Scheduling

    If you've been paying attention you will realise that stalking is a rather expensive, time consuming endevour.

    You might ask, where will I find the time and money to do all of this? (unless you've already managed to join the CIA)

    Well, with your initial investment of time and money you will be able to gather an immense amount of invaluable information about the comings and goings of your stalkee.

    Remember that your life is nothing more than an extension of the person you're stalking and you wont ever be complete if you cant smell their hair, so you need to schedule and mold your whole life around this person.

    Ideally you must pursue the same career or work in the same office building as your stalkee, doing so will greatly simplify everything.

  8. Golden rules

    1. Never make eye contact
    2. Maintain your distance
    3. Know the law (what is a restraining order?)
    4. Never befriend your stalkee


Remember boys and girls, no is only a few letters away from yes.

Happy stalking!




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