Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Orientation change event implementation by jquery mobile in phone gap

Could someone please let me know the right code for orientation change event by jquery mobile in phone gap? Where and how do I implement this orientationChange function?

like image 933
Nishant Avatar asked Apr 05 '12 05:04

Nishant


3 Answers

$(window).bind('orientationchange', _orientationHandler);

then in the _orientationHandler function, have something like:

if(event.orientation){
      if(event.orientation == 'portrait'){
                  //do something
      }
      else if(event.orientation == 'landscape') {
                    //do something
      }
}
like image 93
ghostCoder Avatar answered Oct 13 '22 18:10

ghostCoder


$(window).bind( 'orientationchange', function(e){
    if ($.event.special.orientationchange.orientation() == "portrait") {
        //Do whatever in portrait mode
    } else {
        //Do Whatever in landscape mode
    }
});

You can add the resize event in the event parameter of the bind function, if you're targeting iOS and orientationchange doesn't work. Since changing orientation fires the resize event too.

like image 32
Ettiene Grobler Avatar answered Oct 13 '22 18:10

Ettiene Grobler


The following code should work across all the browsers to detect orientation change. It doesnt uses jquery mobile event but seems to work for most of devices.

1. var isIOS = /safari/g.test(navigator.userAgent.toLowerCase());
2. var ev = isIOS ? 'orientationchange' : 'resize'; 
3. var diff = (window.innerWidth-window.innerHeight);
4. $(window).bind(ev,function(){
5.     setTimeout(function(){
6.         if(diff*((window.innerWidth-window.innerHeight)) < 0)
7.             orientationChanged();
8.     },500);
9. });

Line 2 takes up the resize event for any non-safari browsers since other browsers in other devices take up resize event more consistently than orientation change event. http://www.quirksmode.org/m/table.html

Line 5 performs the check in a timeout since some of the android native browser dont take up the new width immediately.

Line 6 For the orientation change to take place the product of the differences of old and new height and width should be negative.

like image 1
agaase Avatar answered Oct 13 '22 18:10

agaase