Resolving the issue with vue-js click outside function working inside my element

I am currently facing an issue with identifying clicks outside of my element, which happens to be a speed dial item from Vuetify. To address this problem, I have been using directives based on a solution found in this article: Detect click outside element. While I have managed to detect clicks outside and log them successfully, I also encounter the 'clicked outside' log when clicking inside the element. How can I prevent the directive from registering clicks within the element as well? Despite attempting event bubbling or propagation prevention, the issue persists. Any suggestions would be greatly appreciated. Thank you!

<template>
    <v-card>
        <v-speed-dial
            v-click_outside="outside"
            :bottom="true"
            :right="true"
            :direction="direction"
            :transition="transition"
            fixed
        >
        <template v-slot:activator>
            <v-btn
                :class="{ is_active: isActive }"
                color="red"
                fab
                @click="toggleButton"
                dark
                x-large
            > 
                <span  v-if="isActive"><v-icon>mdi-pencil</v-icon></span>
                <v-icon v-else>mdi-plus </v-icon>
            </v-btn>
        </template>
            <v-btn 
                fab 
                dark 
                large 
                color="white" 
                @click.stop="$emit('scrollTo')">
                <v-icon color="#F0BE85">mdi-delete</v-icon>
            </v-btn>
        </v-speed-dial>
    </v-card>
</template>

<script>

export default {
name: 'FloatingButton',
props: {
    display: Boolean,
    ott: Boolean,
    preroll: Boolean,
    gt: Boolean
},
data: () => ({
    direction: 'top',
    fab: false,
    right: true,
    bottom: true,
    transition: 'scale-transition',
    isActive: false,
    backgroundColor: false
}),
methods: {
    toggleButton: function () {
    this.isActive = !this.isActive
    this.backgroundColor = !this.backgroundColor
    },
    outside:function(){
        console.log('clicked outside')
    }
},
directives: {
click_outside:{
    bind:function(el,binding,vnode){
        el.clickOutsideEvent=function(event){
            if (!(el == event.target || el.contains(event.target))) {
                    vnode.context[binding.expression](event);
            }
        }
        document.body.addEventListener('click',el.clickOutsideEvent)
    }
},
unbind:function(el){
    document.body.removeEventListener('click',el.clickOutsideEvent)
}
}
}
</script>

Answer №1

The issue arises because the event targets the "plus" or "pencil" icon which may no longer be present when el.contains() is checked, as the element was switched due to v-if.

To fix this, keep the element consistent with the following code:

<v-btn :class="{ is_active: isActive }" color="red" fab @click="toggleButton" dark x-large>
  <v-icon>{{ isActive ? 'mdi-pencil' : 'mdi-plus' }}</v-icon>
</v-btn>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for exporting meshes with morph changes from a threejs application?

I'm having trouble customizing a mesh and exporting it using the gltfExporter from Threejs. Despite my efforts, the export still includes all morph/shape keys, which I want to remove from the final exported mesh. Attempts to clone the scene/mesh have ...

Issue the token and proceed with redirecting

I am working on an Express app that generates a string token upon receiving a get request and then executes a Python code. The Python code eventually produces a JSON file that needs to be sent in a post request. Since this Python code can be triggered by ...

Tips for adjusting font-family on Vuetify components:

I am looking to change the default Vuetify font family from Roboto, but I only want to do this for a specific element rather than globally. Most solutions I have come across address changing the font family globally, which is not what I need. Can anyone ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

The best practices for utilizing getStaticProps with Firebase

I am completely new to Next.js and am struggling to make the getStaticProps function work properly. import firebase from '../firebase' export default function Home({ posts }) { return ( <div> <h1>All Posts</h1> ...

Different content can be utilized with a single JavaScript code in a Django template by customizing and adapting the code

Working on a web application using Django has presented a challenge. I created an HTML template in Django and embedded JS code for that template as well. The goal is to use this JS code for various types of content displayed with the template, but it' ...

Exploring the seamless integration of okta-vue within VueCLI4

Currently, I am in the process of setting up a Vue authentication page using the Okta-Vue package. The tutorial that I am following can be found here: . For this particular project, I have opted to use VueCLI 4. Following the creation of the project, my ne ...

Press a button and use an if statement to compare the text variable

Can you please assist me with this query? I'm attempting to click on three different buttons with unique IDs, based on a JavaScript string variable. For example: function my_custom_js_func(){ jQuery( "#listViewer" ).click(); }; However, this co ...

Troubleshooting Vue 2: Issues with Template Rendering

Having a component: Vue.component('repo-button', { template: "<div class='socialCircle-item success'><i class='fa fa-comment show_repo' data-check_in='{{ check_in_id }}' data-repo='{{ repo_id }}&ap ...

How can you use JavaScript to determine the width of a CSS element?

Is there a way to make the VarDisk2 element disappear when the width of VarDisk1 exceeds 70? <script> var VarDisk1 = document.querySelector("Disk1"); var VarDisk2 = document.getElementsByClassName("Disk2"); ...

Using jQuery to remove the functionality of a file input button is ineffective

I am having trouble with an input type file element: <input type="file" name="val1" /> And I'm using this jQuery code: $("input[name='val1']").off("click"); However, the above script, which is already included in a $(function() { } ...

Attempting to have the command "npm run dev" generate two separate shell instances

For my nuxt project, I decided to use json-server as the local server. My goal is to automate the process of launching the server and running the project on a separate shell instance by using the command "npm run dev". After some exploration, this is the ...

Obtain individual information from XML

After fetching data from the server using ajax, I am looking to retrieve only a specific part of the data which is the name. How can I modify my code to achieve this? const url = 'https://jsonplaceholder.typicode.com/users' const xhr = new XMLH ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

When the page is loaded, trigger the controller function using AngularJS methodology

Is there a specific way in AngularJS to call a controller function inside the view on page load, or should I follow the classic syntax used in ASP.NET MVC Razor views (such as using ajax)? ...

Safari not centering element with justify-self in CSS grid

My challenge involves adjusting the alignment of a div (mobile menu) that is currently centered using css grid and the justify-self property in chrome. However, when viewed in Safari, it appears on the left side of the screen behind the Instagram icon: ht ...

Issue with Socket IO connecting to incorrect server

As a beginner learning node, I have been gathering information from various sources on the internet. One of the things I wanted to achieve with node was using SendGrid to send emails from the client side. Initially, I had it working by manually entering so ...

Vue fails to trigger a rerender of the list, even when the set function is utilized

I created a list where each item can be removed, and this is how my code looked: Snippet <template v-for="(timeFrame, index) in form.timeFrames"> <el-form-item > ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

The menu was intended to be hidden when the mouse is moved away, but it actually hides

I'm facing an issue with my button and menu functionality. Even though I have coded the menu to hide itself when the mouse leaves, it hides before the mouse even goes over it. Any suggestions on how to resolve this? function showMenu() { var menu ...