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'); } });
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!