albertoperego's blog

iframe: avoid page reload

Say you want the users of your website to be able to add to their profile page an iframe with an external url loaded, their blog for example.
Easy, isn't it?
I did it and then discovered an hidden issue: some popular website, has coded a javascript function that checks if the website is been loaded into an iframe, then it jumps out and load in the main window, with the result that the pour users of your website can't access their profile page anymore!!
What those website have is something like:

if ( top != self.parent )
   top.location = self.parent.location;

What we need to do here to workaround this is handling the onbeforeunload event. This event get fired just before the window where the website is loaded, loads another website or get closed. This means that if an iframe in our website is trying to load itself in the main window, this call get called.
Let's see then what we can do:

window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = '';
  }

  // For Safari
  return '';
};

This script will prompt you an alert message asking if it's your intention to leave the current page.
Because you don't want to have this alert on any time you leave the page, you could use a flag that expires 15-30sec after the creation of the iframe element and then check the value of this flag in the onbeforeunload event function.
Doing so you will receive the confirmation alert only if you leave the website in those 30sec when the iframe is loading which might be the cause of firing the onbeforeunload method.

Unfortunately this code isn't supported (yet) in Safari and gets ignored.

Share and Enjoy:

Javascript: random int between values

I just want to share with you a very very simple function wich should be part of the Math library of function but it's not.
I'm talking about a function which returns a random integer between two values.
Here's an easy function which you can use:

function random(min, max)
{
   return Math.round(min + Math.random()*(max - min))
}

That's all for today!

Share and Enjoy:

Browser Usage Statistics

I just wanted to share with you a link that I monthly check:

It looks like Firefox, Safari and Chrome have together more than 55% of the market and Internet Explorer is going down very quickly, which is a good news for web developers! Yay!
I feel like Google Chrome will soon replace IE, which will horribly die in a couple of years max.

Tags:
Share and Enjoy:

Javascript array of functions

The fun part of Javascript is that functions are variables and at a first glance it might look a weird thing but when you get used to this concept you realize it's a great thing.
Let's see with the following example how to create an array of functions and then fire them sequentially when needed.

var arrayF = [
    [console.log, ['test1']],
    [console.log, ['test2', 'test3']],
    [console.error,['test4']]
];

arrayF.push([alert, ['test5']]);

for(i in arrayF)
    arrayF[i][0].apply(window, arrayF[i][1]);

Handy, isn't it? This thing can be very useful when you need to execute a procedure which include several existing functions.
Also, you could create an array of functions and a caller, which could look like:

function caller(start, end){
  for(i=start;i<end;i++)
    arrayF[i][0].apply(window, arrayF[i][1]);

and then invoke a subset of functions only.

Tags:
Share and Enjoy:

Charles - Web Debugging Proxy

You might be using already the whole day Firebug and wondering how the hell you could have coded without this awesome tool in the past, but as every software, it has bugs and it's not complete.
Thanks god it exists! Don't take me bad.

Sometimes Firebug becomes useless and here it comes Charles to give you a hand.It acts as a proxy, which you install on your client and it save and display everything that pass through the network cable! The great thing is that it saves what you need and offers you several ways to inspect the content saved.
Doing so, it allows you, for example, to inspect the calls made by your new iPhone application to the server, the ajax calls made by all your browsers, email clients, IM desktop applications and so on.

Personally, I do most of the time web work and I've found that firebug it's often enough but as more asynchronous system you build, as more debugging tools you need. This because it becomes harder to track down the calls made and inspect the answers obtained.

For example, it happened recently to me that the web application I was coding for, had a bug in a javascript algorithm, which caused an horrible endless loop with the result of thousands of ajax calls made with no reasons. Firebug couldn't handle this situation, because I couldn't stop it in the middle of the loop and check what was going on, so I switched to Charles and started recording the calls made. Once stopped, I have been able to inspect every single call made, every response and headers. In few minutes I figured out where the bug was and I could patch it quickly.

One of the feature I like in Charles is that it offers you many ways to display the content of a transaction which makes it very powerful for any kind of development/debugging process.
It handles JSON beautifully, offering you a tree-like folder visualization of objects which you can expand.

Definetly worth 40US$.

Share and Enjoy:

Overwrite object functions

Let's say that you have build your class, full of object and variables and it works great, BUT, you need a method of this class to work differently in a certain situation ONLY.
You might know that in object oriented programming you can (and you often have to) use the property called overwriting.
Right, so how does it works in Javascript?

I had today the bad task of debugging someone else code and I've spent hours to figure out what actually was wrong. Here a sample of what I've found:

a = {
    active: function(){
    console.log('day');
    }
};

a.active(); //day

b = a;

b.active = function(){ console.log('night') };

b.active(); //night
a.active(); //night

That's again because b has been associated to the class a doing a=b, which simply gives to b the pointer to a and doesn't create a standalone instance of the class.

I've simply fixed the code using the code as below:

a = {
    active: function(){
    console.log('day');
    }
};

a.active(); //day

temp = a.active;
a.active = function(){ console.log('night') };

a.active();      //night
a.active = temp;
a.active();      //day

I've discussed a similar issue happening with array handling in this post. I hope that this post will save you time when facing the same issue.

Share and Enjoy:

Javascript array: an independent copy

Very very often I do the following error when I need to work on a copy of an array and then the whole code doesn't work and it's always hard to realize what's wrong because it look right but it's not!
Let's have a look at the following code:

var music_genre = ['classic', 'dance', 'metal'];

//copy of the array
var favourite_genre = music_genre;

//extract the last element of the array
favourite_genre.pop();

alert(favourite_genre);  //['classic', 'dance']
alert(music_genre);      //['classic', 'dance'] TOO!!

That's because you need to use the method slice() of the class Array, which returns an independent copy of the array and any modify on it wont affect the original one.
Do something like this:

var favourite_genre = music_genre.slice(0);

favourite_genre.pop();

alert(favourite_genre);  //['classic', 'dance']
alert(music_genre);      //['classic', 'dance', 'metal']

Tags:
Share and Enjoy:

Cross Browser CSS Opacity

I've found that transparency is very often necessary in modern web interfaces. That's because it help the user to understand what's available and what's not and also helps a lot when webpages are rich of non-standard interfaces.
Floating HTML frames and windows, drag & drop elements and photo slideshows do REQUIRE the use of opacity and transparency.

There are basically 2 ways to obtain this, the first is to use a small square image and replicate it in the background:

background: transparent url(images/bg.png) repeat 0 0;

A tipical image used for this scope is 2x2 pixels and has been saved as a PNG or GIF. This is because other formats don't contain the transparency (alpha) information in them.

Another solution consists on building a CSS class containing all of the following proprerties (cross-browser compatible) and attach it to the element we need to fade out:

.translucent{
  -khtml-opacity:.60;
  -ms-filter:”alpha(opacity=60)”;
  -moz-opacity:.60;
  filter:alpha(opacity=60);
  opacity:.60;
}

The first technique presented let you set a gradient faded background while the CSS can't. The advantage of using the CSS solution is that it works better on different browsers AND let you set the opacity of images too, very handy for declare the inactive states of buttons and pictures.

Share and Enjoy:

jQuery elements comparison

Today I got stuck for some minutes with the comparison of two dom elements using jQuery and finally an obvious solution came up.

I needed to check whether or not two dom elements stored in vars where the same thing.

I did first something like this:

// I had something like
var a = $('#logo');
var b = $('#logo');
var c = $('#banner');

alert(a == b); // false!!

alert(a == c); // it's false too!!

Oh, ok, what's wrong with that? Of course, I'm comparing two instances of the same object...which doesn't work!
You might think that the solution would be something like this:

alert(a.is('#logo'));

but the things were more complicated than this example and basically I didn't know the value of the jQuery selector.

So the easy solution is to compare the dom elements themself at the basic javascript element definition, so the check would become:

alert(a[0] == b[0]);   // true!!
alert(a[0] == c[0]);   // false!!

Share and Enjoy:

TextMate for Mac

After 2 years of coding using TextMate, I wish to share with you my love for this great great tool.

If you are a programmer, you own a Mac and you are reading my articles, I bet you have heard about TextMate, since it bacame recently almost THE editor for Macs.

At at first glance this editor might look too basic if you have been using software like Eclipse or NetBeans. It actually took me few months to realize how cool TextMate is.

The software is very lightweight and it's full of features which you don't have to deal with when you are a beginner because they are all optional and hidden. The feeling is to code using the former WordPad for windows but soon you'll find shortcuts for the handy features it has and you'll get in love with it.

Here what I like the most of TextMate:

  1. File Navigator: very quick and handy, anywhere you are, just type command+T and you'll get a list of files in your project, ordered by last opened and with the most recent highlighted. A (focused) textbox let you find the other files, very quickly.
  2. Symbol Navigator: it's very similar to what explained above but it works on methods, function, properties inside files.
  3. Boundles: this is a list of preset list of code which add functionality to TextMate when you are editing your code. To clarify, TM comes with shortcuts to the code syntax routines for many popular languages, plus it has code validators, compilers, and many other tools, like DIFF, SVN, Math functions, shell scripts, FTP, color picker and others.
  4. Low RAM usage: TM wont crash your computer at all, it uses a very tiny amount of memory.

Oh, I forgot to say that you can even blog a post, send html emails, run SQL queries, configure Apache etc etc etc.

It definitely worth to give it a try and re-memorize shortcuts and tricks.

On their website are available many howto videos. Enjoy.

Share and Enjoy: