Hugo Seleiro
Hugo Seleiro

Reputation: 2657

Javascript - Condition not returning True

Its working when i use the portrait mode, but whit the landscape its not working. It returns false. it must return true, could some one help me ? thanks.

    function ismobile(){

    let mobileMode;
    let windowWidth = window.innerWidth;
    let windowHeight = window.innerHeight;

    if (windowWidth <= 375 && windowHeight <= 667 || windowWidth <= 675 && windowHeight <= 375 ) {

        mobileMode = true;

    }else{

        mobileMode = false;

    }   

    console.log("mobileMode " + mobileMode);

}

Upvotes: 0

Views: 63

Answers (3)

Thusitha
Thusitha

Reputation: 3511

If you want to detect if the website is in a mobile browser just don't check for window width and height since latest mobile phones have high resolutions. You can do a simple trick like below using touch events. This method does not depends on the screen orientation.

This is the best approach since it does not depends on browser types.

(function ismobile() {

  let mobileMode;

  if (typeof window.ontouchstart !== 'undefined') {
    //Mobile, portrait or landscape
    mobileMode = true;
  } else {
    //Desktop
    mobileMode = false;
  }

  console.log("Mobile mode: " + mobileMode);

})();

Upvotes: 1

kcode
kcode

Reputation: 402

Try using

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera 
Mini/i.test(navigator.userAgent) ) {
     return true;
}
return false;

if you are trying to check if mobile, if you are just trying to check the size, then just return mobileMode, and group the statements like in @Patrick Cool's answer.

Upvotes: 1

Pslice
Pslice

Reputation: 54

I think you want to group the and statements together like this:

if ((windowWidth <= 375 && windowHeight <= 667) || (windowWidth <= 675 && windowHeight <= 375) ) {

        mobileMode = true;

    }else{

        mobileMode = false;

    }   

Upvotes: 1

Related Questions