HomeJavascriptDetect Device Orientation With Javascript

Detect Device Orientation With Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to detect device orientation and changes in device orientation. To build this project, we need javascript.
 
If you are looking for more such tutorials to improve your javascript skills you can check out this playlist here. This playlist consists of about 100+ javascript projects. The difficulty level of this project varies from easy to quite complex. This makes the playlist suitable for all kinds of javascript learners including javascript beginners to experts.
 

Video Tutorial:

If you are interested to watch a video tutorial instead of reading this blog post you can check out the video down below. Also, subscribe to my youtube channel, where I post a new tutorial every alternate day.

 

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. We create a project folder called – ‘Detect Device Orientation’. Inside this folder, we have two files. These files are index.html and style.css. I have included the javascript code in the body element itself.

HTML:

We begin with the HTML code. The HTML code consists of a div with a class name container. Inside div, we have a button with id – ‘check’ and a p tag with id- ‘status’.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Detect Device Orientation</title>
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <button class="hide" id="check" onclick="orientationChange()">
        Check Orientation
      </button>
      <p id="status"></p>
    </div>
    <!-- Script -->
    <script>
      //Create Initial References
      const statusRef = document.getElementById("status");
      const checkOrientationButton = document.getElementById("check");

      //Create the query
      const potraitMediaQuery = window.matchMedia("(orientation:potrait)");

      //Define a callback function for the event listener (For safari/ios since they don't support screen orientation)
      const mediaOrientationChange = (mediaQuery) => {
        if (!mediaQuery.matches) {
          statusRef.innerText = `Landscape`;
        } else {
          statusRef.innerText = `Potrait`;
        }
      };

      //onchange event would be triggered whenever the orientation  changes
      window.screen.orientation.onchange = orientationChange = () => {
        if (screen.orientation.type.includes("landscape")) {
          statusRef.innerText = `Landscape`;
        } else {
          statusRef.innerText = `Potrait`;
        }
      };

      //However for Firefox it doesn't get fired hence we add buttons to manually display the changed orientation
      window.onload = () => {
        statusRef.innerText = "";
        checkOrientationButton.classList.add("hide");
        if ("mozOrientation" in screen) {
          //For firefox
          //Since we had issues with onchange on firefox the button would simply call the function which we call on change
          checkOrientationButton.classList.remove("hide");
        } else if ("orientation" in screen) {
          //Supported Browsers
          orientationChange();
        } else {
          //For safari
          mediaOrientationChange(potraitMediaQuery);
          potraitMediaQuery.addEventListener("change", mediaOrientationChange);
        }
      };
    </script>
  </body>
</html>

CSS:

Next, we added CSS to this code. You can skip the CSS code as it has nothing to do with the functionality of the code. I have only added it to make the output of our project look more presentable.

/* Only For Styling Purpose*/
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background-color: #4088f4;
}
.container {
  font-size: 2.4em;
  background-color: #ffffff;
  width: 12em;
  height: 12em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 4em 0;
  display: grid;
  place-items: center;
  font-family: "Poppins", sans-serif;
  color: #22203e;
  border-radius: 0.5em;
}
/* IMP */
.hide {
  display: none;
}
@media screen and (max-width: 500px) {
  .container {
    font-size: 20px;
  }
}

Javascript:

Finally, we add functionality to our code using Javascript. We do this in the following steps:

  1. Create initial references
  2. Create the query
  3. Define a callback function for the event listener. This is for safari/ios since they don’t support screen orientation.
  4. Create an onchange event that would be triggered whenever the orientation changes
  5.  Add a button to manually display the changed orientation for firefox. Since we had issues with onchange on firefox, the button would simply call the function which we call on change.

That’s it for this tutorial. If you find any issues while creating this project, you can download the source code by clicking on the ‘Download Code’ button below.

If you have any queries, suggestions or feedback you can comment below.

Happy Coding!

Previous articleMCQ – 6/11/22
Next articleMCQ – 8/11/22
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

six + 13 =

Most Popular