1
\$\begingroup\$

I feel like I can vastly improve this. Any ideas?

// get orientation of device
getOrientation();
// animate
var num = 400;
if( $('body').hasClass("landscape") ) {
 $('.example').animate({'bottom', 0});
} else {
 $('.example').animate({'bottom', num});
}
function getOrientation(){
 switch(window.orientation) { 
 case -90:
 case 90:
 $('body').addClass("landscape");
 // alert('landscape');
 break; 
 default:
 //alert('portrait');
 $('body').addClass("portrait");
 break; 
 }
}
window.onorientationchange = function() {
 getOrientation();
};
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 11, 2012 at 18:39
\$\endgroup\$
1
  • \$\begingroup\$ I think that your window.onorientationchange will never trigger any change. \$\endgroup\$ Commented May 11, 2012 at 20:16

2 Answers 2

2
\$\begingroup\$

Well for starters bind the event using the jQuery standard

var $win = $(window).bind('orientationchange', function(){
 // math.abs to reduce logical operators 
 $('body').removeClass('landscape portrait') // reset
 .addClass(Math.abs(this.orientation) === 90 ? "landscape" : "portrait"); 
});
// now you can trigger the orientation manually on doc ready to set the class
$win.trigger('orientationchange');
var num = 400,
 $body = $('body'),
 $example = $('.example');
if($body.hasClass("landscape"))
 $example.animate({'bottom', 0});
else
 $example.animate({'bottom', num});
answered May 11, 2012 at 19:11
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for this! What is different between binding the event and how I originally had it? \$\endgroup\$ Commented May 11, 2012 at 19:41
  • \$\begingroup\$ There are several benefits adding events using addEventListener vs just assigning a property. For example you can add many listeners instead of just one, etc. But additionally jQuery normalizes the event arg0 passed into the handler so that events behave the same across browsers. \$\endgroup\$ Commented May 11, 2012 at 22:16
1
\$\begingroup\$

Use ternary operators, something like:

 // get orientation of device
getOrientation();
// animate
var num = 400;
$('.example').animate({'bottom', $('body').hasClass("landscape") ? 0 : num});
function getOrientation(){
 $('body').removeAttr('class'); //Removing all classes
 $('body').addClass(90===Math.abs(window.orientation) ? "landscape" : "portrait");
}
window.onorientationchange = function() {
 getOrientation();
};
answered May 11, 2012 at 19:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.