Detecting display’s orientation change on mobile devices with accelerometer: a platform indipendent approach (n95, i900, iPhone…) with javascript

As I wrote, I bought a Samsung i900 Omnia (which as Nokia n95, iPhone and other modern cool mobile phones, has an accelerometer), as a web developer one of the first things that I had in mind was “how can I detect the orientation change (landscape or portrait mode) with javascript or actionscript?”. The first things I thought was:

  1. If the display changes its orientation mode, then the screen width and height must will updated with the new size
  2. If the screen width is smaller than screen height, the device must be in “portrait” mode
  3. Vice versa, if the screen width is bigger than screen height, the device must be in “landscape” mode
  4. The only thing I need is to check the value of screen size and define the orientation mode according to the point 2 and 3

And, as I can see, my deductions was right! I realized a small javascript script, which by using setInterval() function and controlling screen.width and screen.heigth deduces the device orientation mode. Anyway it works actually only with Opera mobile 9.5 (tested only on Samsung Omnia), Internet Explorer Mobile seems unable to interpreting some javascript functions.

This is a piece of my code (the main logic behind):

if (screen.width != width && screen.height != height) {
    width = screen.width;
    height = screen.height;
    mode = width > height ? "landscape" : "portrait";

If you would like to test my script go to

Let me know, thanks ;-)

ps. as soon I will understand about flash capability on my device I will try to implement a custom Actionscript event for the orientation… something like DisplayEvent.DISPLAY_MODE_CHANGE

UPDATE: if you are unable to load try (I have to thanks my friend Andrea Campolonghi for the space)

UPDATE 2: the script works even on Blackberry’s browser (as someone told me) :)

UPDATE 3: it works even on HTC devices (at this point the only problem is internet explorer mobile… I will investigate!)