Home > Web Front-end > CSS Tutorial > How Can I Reliably Close a Dropdown on Both Touch and Desktop Devices?

How Can I Reliably Close a Dropdown on Both Touch and Desktop Devices?

DDD
Release: 2024-12-09 00:00:17
Original
701 people have browsed it

How Can I Reliably Close a Dropdown on Both Touch and Desktop Devices?

Touch Device Support for Document .click Function

When working with responsive websites, it's crucial to ensure that all functionality remains intact on both desktop and touch devices. However, certain events, such as the document .click function, may not work as expected on touchscreens.

Problem:

A sub-navigation dropdown is toggled using a jQuery .click event on the parent list item. However, clicking anywhere on the screen to close the dropdown is not working on touch devices.

Solution:

Modern browsers now support click events for tap interactions, so using document .click should suffice. However, older browsers may require an additional touch event:

$(document).on('click touchstart', function () {
  if ( $(".children").is(":visible")) {
    $("ul.children").slideUp('slow');
  }
});
Copy after login

Explanation:

The touchstart event triggers immediately when a touch is detected, providing a fallback for devices that do not support click events for taps. The click event remains in place to handle both click and tap interactions on modern browsers.

By combining both events, you ensure that the dropdown can be closed by clicking or tapping anywhere on the screen, regardless of the device used.

The above is the detailed content of How Can I Reliably Close a Dropdown on Both Touch and Desktop Devices?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template