-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Dropdown not closing when clicking outside on mobile #824
Comments
Update: Seems like it only affects iOS(?) Tested on three separate Android phones now, and could not reproduce. |
Can confirm, it happens on iOS exclusively |
So after investigating, this has nothing to do with daisyui but iOS itself, Apple doesn't provide proper support for :focus and :focus-within and so, you need to include polyfills if you want the support. i've fixed the issue by doing so |
@effen1337 hi! can you provide the polyfill you used? |
@effen1337 Hi! I'm facing the same issues, would you mind sharing the Polyfills you used? |
@demetrius-mp Turns out I found this polyfill online and it solves all of the problems. EDIT: It didn't end up working properly for me. I think I had been using a different browser on accident :(
|
@san425 awesome! |
@san425 can you provide the link to where you found the polyfill? |
Sorry for the late response @demetrius-mp @san425 @Lekesoldat (and i guess @bosticka needs it too) You need all of these 3 polyfills to make it work (using it in prod and works fine for thousands of iOS users) if ($isApple) {
/**
* ! This user is using annoying Apple products
*/
/**
* ! :focus support
*/
var capturedEvents = [];
var capturing = false;
var redirectedFocusTarget = null;
function getEventTarget(event) {
return event.composedPath()[0];
}
function captureEvent(e) {
if (capturing) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
capturedEvents.unshift(e);
}
}
function hiddenOrInert(element) {
var el = element;
while (el) {
if (el.style.display === 'none' || el.getAttribute('inert') !== null) return true;
el = el.parentElement;
}
return false;
}
/*
* The only mousedown events we care about here are ones emanating from
* (A) anchor links with href attribute,
* (B) non-disabled buttons,
* (C) non-disabled textarea,
* (D) non-disabled inputs of type "button", "reset", "checkbox", "radio", "submit"
* (E) non-interactive elements (button, a, input, textarea, select) that have a tabindex with a numeric value
* (F) audio elements
* (G) video elements with controls attribute
* (H) any element with the contenteditable attribute
*/
function isFocusableElement(el) {
var tag = el.tagName;
return (
!hiddenOrInert(el) &&
((/^a$/i.test(tag) && el.href != null) || // (A)
(/^(button|textarea)$/i.test(tag) && el.disabled !== true) || // (B) (C)
(/^input$/i.test(tag) &&
/^(button|reset|submit|radio|checkbox)$/i.test(el.type) &&
!el.disabled) || // (D)
(!/^(button|input|textarea|select|a)$/i.test(tag) &&
!Number.isNaN(Number.parseFloat(el.getAttribute('tabindex')))) || // (E)
/^audio$/i.test(tag) || // (F)
(/^video$/i.test(tag) && el.controls === true) || // (G)
el.getAttribute('contenteditable') != null) // (H)
);
}
function getLabelledElement(labelElement) {
var forId = labelElement.getAttribute('for');
return forId
? document.querySelector('#' + forId)
: labelElement.querySelector('button, input, keygen, select, textarea');
}
function getFocusableElement(e) {
var currentElement = getEventTarget(e);
var focusableElement;
while (!focusableElement && currentElement !== null && currentElement.nodeType === 1) {
if (isFocusableElement(currentElement)) {
focusableElement = currentElement;
} else if (/^label$/i.test(currentElement.tagName)) {
var labelledElement = getLabelledElement(currentElement);
if (isFocusableElement(labelledElement)) {
focusableElement = labelledElement;
}
}
currentElement = currentElement.parentElement || currentElement.parentNode;
}
return focusableElement;
}
function handler(e) {
var focusableElement = getFocusableElement(e);
if (focusableElement) {
if (focusableElement === document.activeElement) {
// mousedown is happening on the currently focused element
// do not fire the 'focus' event in this case AND
// call preventDefault() to stop the browser from transferring
// focus to the body element
e.preventDefault();
} else {
// start capturing possible out-of-order mouse events
capturing = true;
/*
* enqueue the focus event _after_ the current batch of events, which
* includes any blur events but before the mouseup and click events.
* The correct order of events is:
*
* [this element] MOUSEDOWN <-- this event
* [previously active element] BLUR
* [previously active element] FOCUSOUT
* [this element] FOCUS <-- forced event
* [this element] FOCUSIN <-- triggered by forced event
* [this element] MOUSEUP <-- possibly captured event (it may have fired _before_ the FOCUS event)
* [this element] CLICK <-- possibly captured event (it may have fired _before_ the FOCUS event)
*/
setTimeout(() => {
// stop capturing possible out-of-order mouse events
capturing = false;
// trigger focus event
focusableElement.focus();
// re-dispatch captured mouse events in order
while (capturedEvents.length > 0) {
var event = capturedEvents.pop();
getEventTarget(event).dispatchEvent(new MouseEvent(event.type, event));
}
}, 0);
}
}
}
window.addEventListener('mousedown', handler, { capture: true });
window.addEventListener('mouseup', captureEvent, { capture: true });
window.addEventListener('click', captureEvent, { capture: true });
/**
* ! :focus-within polyfill attempt
*/
function polyfill() {
/** @const */ var CLASS_NAME = 'focus-within';
/** @const */ var WHITE_SPACE = ['\n', '\t', ' ', '\r'];
/**
* Calculate the entire event path.
*
* @param {Element} node
* @return {Array} computedPath
*/
function computeEventPath(node) {
var path = [node];
var parent = null;
while ((parent = node.parentNode || node.host || node.defaultView)) {
path.push(parent);
node = parent;
}
return path;
}
/**
* Add user defined attribute to element retaining any previously
* applied attributes. Attribute can be the 'class' attribute for
* compatibility reasons.
*
* @param {string} value
* @return {function(Element)} callback
*/
function addClass(value) {
return function (el) {
var attributes =
typeof el.getAttribute !== 'undefined' ? el.getAttribute('class') || '' : undefined;
if (typeof attributes !== 'undefined' && attributes.indexOf(value) === -1) {
el.setAttribute('class', attributes.concat(' ', value).trim());
}
};
}
/**
* Remove user defined attribute value or entire attribute if last one.
* Attribute can be the 'class' attribute for compatibility reasons.
*
* @param {string} value
* @return {function(Element)} callback
*/
function removeClass(value) {
return function (el) {
var attributes =
typeof el.getAttribute !== 'undefined' ? el.getAttribute('class') || '' : undefined;
if (attributes) {
var index = attributes.indexOf(value);
// Check if `value` exists in `attributes` and it is either
// at the start or after a whitespace character. This stops
// "focus-within" being remove from "js-focus-within".
if (
index >= 0 &&
(index === 0 || WHITE_SPACE.indexOf(attributes.charAt(index - 1)) >= 0)
) {
var newAttributes = attributes.replace(value, '').trim();
newAttributes === ''
? el.removeAttribute('class')
: el.setAttribute('class', newAttributes);
}
}
};
}
/**
* Attach event listerns to initiate polyfill
* @return {boolean}
*/
function load() {
var handler = function (e) {
var running;
/**
* Request animation frame callback.
* Remove previously applied attributes.
* Add new attributes.
*/
function action() {
running = false;
if ('blur' === e.type) {
Array.prototype.slice
.call(computeEventPath(e.target))
.forEach(removeClass(CLASS_NAME));
}
if ('focus' === e.type) {
Array.prototype.slice
.call(computeEventPath(e.target))
.forEach(addClass(CLASS_NAME));
}
}
if (!running) {
window.requestAnimationFrame(action);
running = true;
}
};
document.addEventListener('focus', handler, true);
document.addEventListener('blur', handler, true);
addClass('js-focus-within')(document.body);
return true;
}
try {
return typeof window !== 'undefined' && !document.querySelector(':' + CLASS_NAME);
} catch (error) {
return load();
}
}
polyfill();
/**
* ! :focus-visible polyfill WICG support
*/
function applyFocusVisiblePolyfill(scope) {
var hadKeyboardEvent = true;
var hadFocusVisibleRecently = false;
var hadFocusVisibleRecentlyTimeout = null;
var inputTypesAllowlist = {
text: true,
search: true,
url: true,
tel: true,
email: true,
password: true,
number: true,
date: true,
month: true,
week: true,
time: true,
datetime: true,
'datetime-local': true
};
/**
* Helper function for legacy browsers and iframes which sometimes focus
* elements like document, body, and non-interactive SVG.
* @param {Element} el
*/
function isValidFocusTarget(el) {
if (
el &&
el !== document &&
el.nodeName !== 'HTML' &&
el.nodeName !== 'BODY' &&
'classList' in el &&
'contains' in el.classList
) {
return true;
}
return false;
}
/**
* Computes whether the given element should automatically trigger the
* `focus-visible` class being added, i.e. whether it should always match
* `:focus-visible` when focused.
* @param {Element} el
* @return {boolean}
*/
function focusTriggersKeyboardModality(el) {
var type = el.type;
var tagName = el.tagName;
if (tagName === 'INPUT' && inputTypesAllowlist[type] && !el.readOnly) {
return true;
}
if (tagName === 'TEXTAREA' && !el.readOnly) {
return true;
}
if (el.isContentEditable) {
return true;
}
return false;
}
/**
* Add the `focus-visible` class to the given element if it was not added by
* the author.
* @param {Element} el
*/
function addFocusVisibleClass(el) {
if (el.classList.contains('focus-visible')) {
return;
}
el.classList.add('focus-visible');
el.setAttribute('data-focus-visible-added', '');
}
/**
* Remove the `focus-visible` class from the given element if it was not
* originally added by the author.
* @param {Element} el
*/
function removeFocusVisibleClass(el) {
if (!el.hasAttribute('data-focus-visible-added')) {
return;
}
el.classList.remove('focus-visible');
el.removeAttribute('data-focus-visible-added');
}
/**
* If the most recent user interaction was via the keyboard;
* and the key press did not include a meta, alt/option, or control key;
* then the modality is keyboard. Otherwise, the modality is not keyboard.
* Apply `focus-visible` to any current active element and keep track
* of our keyboard modality state with `hadKeyboardEvent`.
* @param {KeyboardEvent} e
*/
function onKeyDown(e) {
if (e.metaKey || e.altKey || e.ctrlKey) {
return;
}
if (isValidFocusTarget(scope.activeElement)) {
addFocusVisibleClass(scope.activeElement);
}
hadKeyboardEvent = true;
}
/**
* If at any point a user clicks with a pointing device, ensure that we change
* the modality away from keyboard.
* This avoids the situation where a user presses a key on an already focused
* element, and then clicks on a different element, focusing it with a
* pointing device, while we still think we're in keyboard modality.
* @param {Event} e
*/
function onPointerDown(e) {
hadKeyboardEvent = false;
}
/**
* On `focus`, add the `focus-visible` class to the target if:
* - the target received focus as a result of keyboard navigation, or
* - the event target is an element that will likely require interaction
* via the keyboard (e.g. a text box)
* @param {Event} e
*/
function onFocus(e) {
// Prevent IE from focusing the document or HTML element.
if (!isValidFocusTarget(e.target)) {
return;
}
if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {
addFocusVisibleClass(e.target);
}
}
/**
* On `blur`, remove the `focus-visible` class from the target.
* @param {Event} e
*/
function onBlur(e) {
if (!isValidFocusTarget(e.target)) {
return;
}
if (
e.target.classList.contains('focus-visible') ||
e.target.hasAttribute('data-focus-visible-added')
) {
// To detect a tab/window switch, we look for a blur event followed
// rapidly by a visibility change.
// If we don't see a visibility change within 100ms, it's probably a
// regular focus change.
hadFocusVisibleRecently = true;
window.clearTimeout(hadFocusVisibleRecentlyTimeout);
hadFocusVisibleRecentlyTimeout = window.setTimeout(function () {
hadFocusVisibleRecently = false;
}, 100);
removeFocusVisibleClass(e.target);
}
}
/**
* If the user changes tabs, keep track of whether or not the previously
* focused element had .focus-visible.
* @param {Event} e
*/
function onVisibilityChange(e) {
if (document.visibilityState === 'hidden') {
// If the tab becomes active again, the browser will handle calling focus
// on the element (Safari actually calls it twice).
// If this tab change caused a blur on an element with focus-visible,
// re-apply the class when the user switches back to the tab.
if (hadFocusVisibleRecently) {
hadKeyboardEvent = true;
}
addInitialPointerMoveListeners();
}
}
/**
* Add a group of listeners to detect usage of any pointing devices.
* These listeners will be added when the polyfill first loads, and anytime
* the window is blurred, so that they are active when the window regains
* focus.
*/
function addInitialPointerMoveListeners() {
document.addEventListener('mousemove', onInitialPointerMove);
document.addEventListener('mousedown', onInitialPointerMove);
document.addEventListener('mouseup', onInitialPointerMove);
document.addEventListener('pointermove', onInitialPointerMove);
document.addEventListener('pointerdown', onInitialPointerMove);
document.addEventListener('pointerup', onInitialPointerMove);
document.addEventListener('touchmove', onInitialPointerMove);
document.addEventListener('touchstart', onInitialPointerMove);
document.addEventListener('touchend', onInitialPointerMove);
}
function removeInitialPointerMoveListeners() {
document.removeEventListener('mousemove', onInitialPointerMove);
document.removeEventListener('mousedown', onInitialPointerMove);
document.removeEventListener('mouseup', onInitialPointerMove);
document.removeEventListener('pointermove', onInitialPointerMove);
document.removeEventListener('pointerdown', onInitialPointerMove);
document.removeEventListener('pointerup', onInitialPointerMove);
document.removeEventListener('touchmove', onInitialPointerMove);
document.removeEventListener('touchstart', onInitialPointerMove);
document.removeEventListener('touchend', onInitialPointerMove);
}
/**
* When the polfyill first loads, assume the user is in keyboard modality.
* If any event is received from a pointing device (e.g. mouse, pointer,
* touch), turn off keyboard modality.
* This accounts for situations where focus enters the page from the URL bar.
* @param {Event} e
*/
function onInitialPointerMove(e) {
// Work around a Safari quirk that fires a mousemove on <html> whenever the
// window blurs, even if you're tabbing out of the page. ¯\_(ツ)_/¯
if (e.target.nodeName && e.target.nodeName.toLowerCase() === 'html') {
return;
}
hadKeyboardEvent = false;
removeInitialPointerMoveListeners();
}
// For some kinds of state, we are interested in changes at the global scope
// only. For example, global pointer input, global key presses and global
// visibility change should affect the state at every scope:
document.addEventListener('keydown', onKeyDown, true);
document.addEventListener('mousedown', onPointerDown, true);
document.addEventListener('pointerdown', onPointerDown, true);
document.addEventListener('touchstart', onPointerDown, true);
document.addEventListener('visibilitychange', onVisibilityChange, true);
addInitialPointerMoveListeners();
// For focus and blur, we specifically care about state changes in the local
// scope. This is because focus / blur events that originate from within a
// shadow root are not re-dispatched from the host element if it was already
// the active element in its own scope:
scope.addEventListener('focus', onFocus, true);
scope.addEventListener('blur', onBlur, true);
// We detect that a node is a ShadowRoot by ensuring that it is a
// DocumentFragment and also has a host property. This check covers native
// implementation and polyfill implementation transparently. If we only cared
// about the native implementation, we could just check if the scope was
// an instance of a ShadowRoot.
if (scope.nodeType === Node.DOCUMENT_FRAGMENT_NODE && scope.host) {
// Since a ShadowRoot is a special kind of DocumentFragment, it does not
// have a root element to add a class to. So, we add this attribute to the
// host element instead:
scope.host.setAttribute('data-js-focus-visible', '');
} else if (scope.nodeType === Node.DOCUMENT_NODE) {
document.documentElement.classList.add('js-focus-visible');
document.documentElement.setAttribute('data-js-focus-visible', '');
}
}
// It is important to wrap all references to global window and document in
// these checks to support server-side rendering use cases
// @see https://github.com/WICG/focus-visible/issues/199
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// Make the polyfill helper globally available. This can be used as a signal
// to interested libraries that wish to coordinate with the polyfill for e.g.,
// applying the polyfill to a shadow root:
window.applyFocusVisiblePolyfill = applyFocusVisiblePolyfill;
// Notify interested libraries of the polyfill's presence, in case the
// polyfill was loaded lazily:
var event;
try {
event = new CustomEvent('focus-visible-polyfill-ready');
} catch (error) {
// IE11 does not support using CustomEvent as a constructor directly:
event = document.createEvent('CustomEvent');
event.initCustomEvent('focus-visible-polyfill-ready', false, false, {});
}
window.dispatchEvent(event);
}
if (typeof document !== 'undefined') {
// Apply the polyfill to the global document, so that no JavaScript
// coordination is required to use the polyfill in the top-level document:
applyFocusVisiblePolyfill(document);
}
} Notes:
have fun |
Thank you @effen1337. Using sveltejs, I had to change all of the var declarations to let declarations or I received compile error Not Implemented undefined. |
@bosticka Are you applying this "on" mounting or before? from my testing, it works "on" mounting (inside |
Same problem here. Edit: |
@serkodev that solution worked for me, as odd as that is. |
@serkodev Genius! Thank you |
This isn't working for me, tried on direct parent elements of the navbar that have dropdown, and directly on the body |
tabindex="0" on body tag , works for me , thank you for the solution!
…Sent from my iPhone
On 13 Dec 2022, at 19:08, Bryant ***@***.***> wrote:
tabindex="0"
|
Stumbled on this issue through Google and ended up solving the issue in another way so I wanted to share it here. I should also preface that at least in Chrome the polyfill from @effen1337 gave me a JS error that on the line My personal app is a Nuxt v3 (Vue v3) application. I solved it by adding the following to my primary tailwind CSS file: .dropdown,
.dropdown-content,
.dropdown .dropdown-content,
.dropdown.dropdown-open .dropdown-content,
.dropdown.dropdown-hover:hover .dropdown-content,
.dropdown:not(.dropdown-hover):focus .dropdown-content,
.dropdown:not(.dropdown-hover):focus-within .dropdown-content {
pointer-events: auto;
visibility: visible;
opacity: 1;
} This was inspired by the proposed solution of #872 Which means the dropdown is always visible. But of course, we do not actually want that so instead I manage the visibility through Vue JS: First create a composable hook to store the state: export const useOpenDropdown = () => useState<boolean>('open-dropdown', () => false); <template>
<nav class="navbar bg-base-100 sticky top-0 z-20">
<div class="navbar-start flex items-center">
<div class="dropdown">
<label tabindex="0" class="btn btn-ghost lg:hidden" @click="toggleOpenDropdown">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16" />
</svg>
</label>
<ul tabindex="0" v-if="openDropdown === true" class="menu menu-compact dropdown-content mt-3 p-2 shadow bg-base-100 rounded-box w-52">
<li v-if="$route.path !== '/'">
<nuxt-link to="/" @click="toggleOpenDropdown">Home</nuxt-link>
</li>
<li>
<nuxt-link to="/post" @click="toggleOpenDropdown">Post</nuxt-link>
</li>
<li>
<nuxt-link to="/update" @click="toggleOpenDropdown">Update</nuxt-link>
</li>
<li>
<nuxt-link to="/configure/webhooks" @click="toggleOpenDropdown">Configure Webhooks</nuxt-link>
</li>
<li>
<nuxt-link to="/configure/roles" @click="toggleOpenDropdown">Configure Roles</nuxt-link>
</li>
</ul>
</div>
<nuxt-link to="/" class="btn btn-ghost normal-case text-xl flex justify-start items-center"
><nuxt-img src="/images/gem.svg" style="height: 24px" /><span class="ml-2">Sapphire</span></nuxt-link
>
</div>
</nav>
</template>
<script setup lang="ts">
const openDropdown = useOpenDropdown();
function toggleOpenDropdown() {
openDropdown.value = !openDropdown.value;
}
</script> Now whenever any of the router Lastly, there is also a bit of trickery required in <template>
<div class="h-full" @click="closeDropdownIfOpen">
<sections-app-navbar />
</div>
</template>
<script setup lang="ts">
const openDropdown = useOpenDropdown(); // pulling in the same state as before so it is linked
const prevValue = useState<boolean | null>('prev-value', () => null); // an extra bit of state to track the previous value
function closeDropdownIfOpen() {
if ((prevValue === null && openDropdown.value) || (prevValue.value && openDropdown.value)) {
openDropdown.value = false;
}
prevValue.value = openDropdown.value;
}
</script> Here we use Maybe not the cleanest solution because it removes the pure CSS-ness, but at least it works on all devices. Sidenote that I had to also do a similar thing for the |
This was very frustrating for me, tabindex="-1" on body tag solved it. Should definitely be in the docs |
adding a tabindex="0" to the container or root element |
This topic is closed but I had the same issue with DaisyUI 4.9 and Nuxt 3 - so I am sharing my solution:
// HeaderComponent.vue
<script setup>
import { vOnClickOutside } from '@vueuse/components'
</script>
<div class="navbar-center mt-2 hidden lg:flex">
<ul class="menu menu-horizontal px-1">
<template v-for="item in menuItems" key="item.href">
<!-- HERE WE ADD THE DIRECTIVE: -->
<li v-if="item.children" class="menu-link-item" v-on-click-outside="closeDropdown">
<!-- /DIRECTIVE: -->
<details :open="false">
<summary tabindex="0" role="button">
{{ item.name }}
</summary>
<ul class="menu dropdown-content min-w-52 p-2" tabindex="0">
<li v-for="childItem in item.children">
<NuxtLink
class="menu-link-item"
:href="childItem.href"
:title="childItem.name"
>{{ childItem.name }}</NuxtLink
>
</li>
</ul>
</details>
</li>
<li v-else class="menu-link-item">
<NuxtLink :href="item.href" :title="item.name">{{ item.name }}</NuxtLink>
</li>
</template>
</ul>
</div>
// HeaderComponent.vue
<script setup>
import { vOnClickOutside } from '@vueuse/components'
const closeDropdown = () => {
const dropdowns = document.querySelectorAll('.menu-link-item details[open]')
dropdowns.forEach((dropdown) => {
dropdown.removeAttribute('open')
})
}
</script>
|
this is my solution for index focus dropdown can toggleable:
|
Tried copy pasting the various examples from the dropdown-page. In both Brave Mobile and Safari I was unable to close the dropdowns by clicking outside.
A live example at holtet.vercel.app (It's the theme picker in the navbar)
Here's my implementation of the switcher (heavy inspired by daisyui's..)
EDIT:
It works if you click a link, but not other general content. Works well on desktop browsers.
The text was updated successfully, but these errors were encountered: