2

Disclaimer: I am not a javascript or jQuery expert.

This is probably an easy problem to solve, as it's just a small fix I can't figure out. I am implementing a site that is horizontal if the browser is in landscape mode, and vertical if in portrait. CSS changes are not an issue as that is easy with media queries. The problem I run into is when I want to only run a specific script when the screen is in landscape mode. Next problem I run into is that I don't just want this to work on mobile, but I also want it to be responsive in a standard browser as well; i.e. detect when the screen width > screen height and run said script. Here is my code so far:

var height = $(window).height();
var width = $(window).width();
if (width > height) {
    //run landscape script
} else {
    //run portrait script
};

This is working just fine to detect orientation when the page loads, but it doesn't change when the screen is resized since the script is not bound to window.resize. That being said, it is also not working when I bind it to window.resize.

Is there a better way to go about this? Or do I just need to fix up what is already here?

1
  • 2
    I'm not very familiar with writing JavaScript for mobile devices as I mostly write it for desktop web applications. However, you may be able to find something useful in jQuery Mobile since you're already using jQuery anyway. It's a jQuery framework dedicated to mobile device support. Hope this helps. Best of luck. Commented Dec 14, 2012 at 16:29

1 Answer 1

3

In case somebody else runs into this problem in the future, I'll post what solved my problem.

When I attempted to add the resize event to the function, my code looked like this:

$(window).on('resize', function() {
    var height = $(window).height();
    var width = $(window).width();
    if (width > height) {
        //run landscape script
    } else {
        //run portrait script
    };
)};

This worked just fine, but it did not appear that way because the script was only being fired when the browser resized. While this is essential, the script also needs to fire when the page loads. My solution was just to add 'load' to the event:

$(window).on('resize load', function() {
    var height = $(window).height();
    var width = $(window).width();
    if (width > height) {
        //run landscape script
    } else {
        //run portrait script
    };
)};
Sign up to request clarification or add additional context in comments.

1 Comment

You should check what device supports: resize or orientationchange

Your Answer

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.