\$\begingroup\$
\$\endgroup\$
1
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
2 Answers 2
\$\begingroup\$
\$\endgroup\$
2
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
-
\$\begingroup\$ Thanks for this! What is different between binding the event and how I originally had it? \$\endgroup\$cuserjuicer– cuserjuicer2012年05月11日 19:41:57 +00:00Commented 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\$Josiah Ruddell– Josiah Ruddell2012年05月11日 22:16:29 +00:00Commented May 11, 2012 at 22:16
\$\begingroup\$
\$\endgroup\$
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();
};
default
window.onorientationchange
will never trigger any change. \$\endgroup\$