Skip to content Skip to sidebar Skip to footer

Dropdown Menu Css / Js On Ipad

I'm working on a website with a simple and pure css dropdown menu. That website is supposed to be used on desktop and on Ipads. My dropdown menu uses :hover pseudo-class and issue

Solution 1:

The :hover pseudo-class behaves differently on touch screen devices. When the user touches an element, the browser triggers and keeps the state :hover until another pseudo-class is triggered. Thus, when the user touches another element on the page, a different pseudo-class is triggered by the browser and the drop-down menu becomes hidden. Most of the time, it is the :active pseudo-class that is triggered.

However, as explained on the Safari Developer Library, Mobile Safari doesn't trigger the :active pseudo-class unless a touch event is attached to the element:

On iOS, mouse events are sent so quickly that the down or active state is never received. Therefore, the :active pseudo state is triggered only when there is a touch event set on the HTML element—for example, when ontouchstart is set on the element...

To fix this, you can add a touchstart listener to your document in order to trigger the :active pseudo-class:

document.addEventListener('touchstart', function() {});

Solution 2:

Here a solution, ask if you want explanation.

<navid='nav'>
...
<script>functionhideDropDownMenu(e) {
  var element = e.target;
  var parent = element.parentNode;
  var mustHide = false;
  while (parent != null && !mustHide) {
    mustHide = element.id === 'nav';
    element = element.parentNode;
  }
  var subMenus = document.getElementsByClassName('subMenu');
  var i = 0;
  for (i = 0; i < subMenus.length; i++) {
    var subMenu = subMenus[i];
    subMenu.style = mustHide ? 'none !important' : 'block'; // not sure if the !import is optionnal
  }
}

document.body.addEventListener('click', hideDropDownMenu);
</script>

Solution 3:

As I posted in another question:

I solved this problem by adding a tabindex to the <body> tag, like this:

<bodytabindex="0">

This little trick allowed iPad Safari to focus on the body when it's tapped on, and remove the focus from the dropdown menu.

No Javascript required. 😊

Post a Comment for "Dropdown Menu Css / Js On Ipad"