'vue 3 click outside directive prevent to close a specific content (sidebar) when click inside
I am using this directive in vue 3 for click outside
export default {
beforeMount(el, binding, vnode) {
el.clickOutsideEvent = function(event) {
if (!(el === event.target || el.contains(event.target))) {
binding.value(event, el);
}
};
document.body.addEventListener('click', el.clickOutsideEvent);
},
unmounted(el) {
document.body.removeEventListener('click', el.clickOutsideEvent);
}
};
I am using most of it for dropdown. When click outside or click on the item from dropdown list it close the dropdown.
I want to use it on a sidebar where there are some input fields (select, radio, etc.... for filtering).
It works when I click the button to show the sidebar, and when click outside the sidebar it close it. The directive it works like it should.
but .... I want to change that directive (or create another one specially for this sidebar) when click on the sidebar content (anywhere) or click on input elements the sidebar ... not to close the sidebar (only when click outside the sidebar to close it).
How can I do that ?
UPDATE
I was thinking to add a specific class name to every element from sidebar and add this to if condition
if (!(el === event.target || el.contains(event.target) || event.target.classList.contains('specific-sidebar-class-name')))
Solution 1:[1]
I have added and id to the sidebar filter component .... and now when click inside (anywhere the sidebar) it will not close
export default {
beforeMount(el, binding, vnode) {
el.clickOutsideEvent = function(event) {
let sidebarFilter = document.getElementById('sidebar-filter-component')
let clickedInsideSidebar = sidebarFilter && (event.target === sidebarFilter || sidebarFilter.contains(event.target))
if (!(el === event.target || el.contains(event.target) || clickedInsideSidebar)) {
binding.value(event, el);
}
};
document.body.addEventListener('click', el.clickOutsideEvent);
},
unmounted(el) {
document.body.removeEventListener('click', el.clickOutsideEvent);
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | calin24 |
