How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately.

Initially, I created a function that increases the column width when double-clicking on the header. Surprisingly, it only works for the first double click. Subsequent clicks (4 or 6 times) do not trigger any action after the initial one. Is there a way to reset the event so that the function is triggered again after two more clicks?

While moving the mouse, I noticed that multiple consecutive double clicks can be performed. However, this behavior is not the desired outcome.

Find below the snippet of code:

<th 
  v-for="c in data.columns" 
  v-if="visiblecolumns.includes(c)" 
  v-on:dblclick="COLUMN_DEFINITION[c]+=50" 
  :style="{ 'min-width': COLUMN_DEFINITION[c] + 'px', 'max-width': COLUMN_DEFINITION[c] + 'px' }">
    {{ c }}
</th>

Answer №1

<th 
  v-for="c in data.columns" 
  v-if="visiblecolumns.includes(c)" 
  @click="changeColumnDefinition" 
  :style="{ 'min-width': COLUMN_DEFINITION[c] + 'px', 'max-width': COLUMN_DEFINITION[c] + 'px' }">
    {{ c }}
</th>

Referenced from: How to manage click and double-click events on the same element in Vue.js, with input from @JBDouble05

new Vue({
    el: '#app',
    data: {
        counter: 0,  // keeps track of clicks
        timer: null  // Must be defined here for access in both clicks
    },    
    methods: {
        changeColumnDefinition: function(event){
            var self = this
            this.counter++ 
            if(this.counter == 1) {
                this.timer = setTimeout(function() {
                    // DO NOTHING EXCEPT RESET IF THERE'S ONLY ONE CLICK                    
                    self.counter = 0
                }, 500);  // adjust delay as needed
            }else{
                clearTimeout(this.timer);  
                // COLUMN_DEFINITION[c]+=50
                self.counter = 0;
            }         
        }      
    }
});

NOTE This extends beyond the original question, but:

I would recommend encapsulating this within a component, especially if you have multiple headers. If an external function needs to be called, simply use:

this.$emit('someEvent', someValue);

To emit an event and then handle it in your component like this:

<my-awesome-component @someEvent="someFunction"></my-awesome-component>

Answer №2

To track double clicks, create a variable that increments whenever the v-on:dblclick event is triggered. Then, in your JavaScript file, add an event listener to check if the variable modulus 2 equals 0 - indicating two double clicks. If not, it means an odd number of clicks occurred and you can reset the event. It may sound complicated, but feel free to ask for clarification or simplification.

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

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

Encountering a React Runtime issue: The element type is invalid, expecting a string for built-in components or a class/function for composite components

Here is a glimpse of my code: import { React, useState, useEffect } from 'react'; import { GoogleMapReact } from 'google-map-react'; import styles from './Location.module.scss'; import pinstyles from './TheMap.module.scss ...

Tips for navigating to a new route after a successful AJAX request

Hey everyone, I'm new to Vue and currently using version 2.5. I have been doing a lot of research online and came across this.$router.push('/login') for redirection, but it was not working for me. This has left me a bit confused on how to ac ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...

Filtering a list in AngularJS based on a property of an object with a filter applied on it

I am facing an issue with filtering a list of objects based on their properties using the filter filter. The problem arises when certain object properties have filters applied to them that alter their displayed format (such as the formatDate filter in the ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

Ways to modify a global variable across all components

I am looking to implement an automatic system that changes the page title according to the view I am on. Initially, I considered using a global variable in my main.js file: // MAIN.JS FILE const App = createApp(AppVue).use(router) App.config.globalProper ...

The final value is always returned by jQuery's each method

Is there a way to prevent the .each() function from selecting the last value every time it runs? var items = ["item1", "item2", "item3"]; $("#list li").each(function() { var addedClass; if ($(this).hasClass("one")) { addedClass = "red"; } else ...

Where is the location of the directory on the hard drive that was created using the getDirectory() method in HTML5?

I have been working on creating, deleting, and reading directories but I am unsure of where they are located on the hard drive. fs.root.getDirectory('something', {create: true}, function(dirEntry) { alert('Congratulations! You have succes ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

Exporting Canvas data without the alpha channel

I am looking for a way to resize images that are uploaded in the browser. Currently, I am utilizing canvas to draw the image and then resize it using the result from the toDataURL method. A simplified version of the code (without the upload section) looks ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

Encountering a 'unknown column' error while using MySQL on a Windows operating system

A query is being executed on Node.Js with MySQL, resulting in the following: SELECT COUNT(DISTINCT t.uid) AS usersCount, COUNT(*) AS workingDaysCount FROM ( SELECT d.date, u.id AS uid, CASE TIMESTAMPDIFF(day, SUBDATE(d.date, WEEKDAY(d.date) ...