Skip to content

Commit

Permalink
Merge pull request #42 from ryanhcode/issue-40
Browse files Browse the repository at this point in the history
Hide dropdown widget when clicking outside of it
  • Loading branch information
SanderMertens authored Jan 30, 2025
2 parents 2078075 + ae0bde3 commit 4228fd4
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions etc/js/components/widgets/dropdown.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<template>
<div class="dropdown">
<div class="dropdown" ref="dropdown">
<div class="dropdown-container" @click="onClick">
<div class="dropdown-text noselect">
<template v-if="activeItem">
Expand Down Expand Up @@ -28,7 +28,7 @@ export default { name: "dropdown" };
</script>

<script setup>
import { defineProps, defineModel, onMounted, ref } from 'vue';
import { defineProps, defineModel, onMounted, onBeforeUnmount, ref } from 'vue';
const props = defineProps({
items: {type: Array, required: true},
Expand All @@ -38,16 +38,31 @@ const activeItem = defineModel("active_item");
const showList = ref(false);
const dropdown = ref(null);
onMounted(() => {
if (!activeItem.value) {
activeItem.value = props.items[0];
}
window.addEventListener('click', onWindowClick)
});
onBeforeUnmount(() => {
window.removeEventListener('click', onWindowClick)
});
function onClick() {
showList.value = true;
}
function onWindowClick(event) {
// Close if the dropdown doesn't contain the clicked element
if (!dropdown.value.contains(event.target)) {
showList.value = false;
}
}
function onSelect(item) {
activeItem.value = item;
showList.value = false;
Expand Down

0 comments on commit 4228fd4

Please sign in to comment.