Home >Web Front-end >CSS Tutorial >How Can a Touch Device Trigger `document.click` to Close a Dropdown Menu?
Document .click Function for Touch Devices
Question: How can a touch device trigger the document.click function to close a dropdown menu initiated by a click event?
Answer:
Modern browsers, such as Chrome and Firefox, trigger the click event for touch inputs. This eliminates the need for additional touchstart or touchend events. Simply use:
$(document).on('click', function () { ... });
Explanation:
Older browsers interpreted touch inputs differently, considering them as distinct events. To account for this, an event handler like the following was used:
$(document).on('click touchstart', function () { ... });
However, with the advent of touch-friendly browsers, the touchstart event is no longer necessary. The click event alone suffices.
Additional Note:
The provided example uses the event delegation technique with .on() to bind the click handler to the entire document. This ensures that the click event is captured even when the menu is dynamically added or removed.
The above is the detailed content of How Can a Touch Device Trigger `document.click` to Close a Dropdown Menu?. For more information, please follow other related articles on the PHP Chinese website!