Blog>
Snippets

Handling Orientation Changes

Adjust touch event coordinates when an orientation change occurs to ensure consistent touch event handling across landscape and portrait modes.
var currentOrientation = window.orientation;

// Function to handle touch event
function handleTouchEvent(event) {
  var touch = event.touches[0]; // Get the first touch
  var x, y;

  switch(currentOrientation) {
    case 0: // Portrait
      x = touch.pageX;
      y = touch.pageY;
      break;
    case 90: // Landscape (clockwise)
    case -90: // Landscape (counterclockwise)
      x = touch.pageY;
      y = window.innerWidth - touch.pageX;
      break;
    default:
      x = touch.pageX;
      y = touch.pageY;
  }

  // Process the coordinates (x, y)
  console.log('Touch coordinates:', x, y);
}

// Listen for touch events on the element
var myElement = document.getElementById('myElement');
myElement.addEventListener('touchstart', handleTouchEvent);

// Listen for orientation change and update the current orientation
window.addEventListener('orientationchange', function() {
  currentOrientation = window.orientation;
  // Additional logic can be added here to adjust the UI, if necessary
});
This code sets up an event listener for touchstart events on an element and adjusts the x and y coordinates based on the current screen orientation. It also listens for changes in orientation to update the currentOrientation variable.