Search code examples
jqueryorientationscreen-orientationdevice-orientation

Evaluate orientationEvent and setting a value?


If I have an onChange function firing when an orientation change has happened, how do I set a value within the onChange that will update a jquery selector. For instance:

  $(document).ready(function(){    
    var onChanged = function() {
            if(window.orientation == 90 || window.orientation == -90){
                image = '<img src="images/land_100.png">';
            }else{
                image = '<img src="images/port_100.png">';
            }
     }
        $(window).bind(orientationEvent, onChanged).bind('load', onChanged);
        $('#bgImage').html(image); //won't update image
   });

Solution

  • You need to put the update to the image inside the onChanged function so that every time the orientation changes, the image HTML will be changed.

    $(document).ready(function(){   
    
       // The event for orientation change
       var onChanged = function() {
    
          // The orientation
          var orientation = window.orientation,
    
          // If landscape, then use "land" otherwise use "port"
          image = orientation == 90 || orientation == -90 ? "land" : "port";
    
          // Insert the image
          $('#bgImage').html('<img src="images/'+image+'_100.png">');
    
       };
    
       // Bind the orientation change event and bind onLoad
       $(window).bind(orientationEvent, onChanged).bind('load', onChanged);
    
    });