Stop button from being clicked inside a div when mouse hovers over it

I am facing an issue with a div containing a mouseenter event and a button inside it with a click event. The concept is that when the user hovers over the div triggering the mouseenter event, the div becomes "active", allowing the button to be visible and clickable.

Everything works perfectly on desktop, but on mobile devices, because of the mouseenter event, clicking where the button should appear while the div is inactive results in accidentally clicking the button itself.

I want to prevent users from mistakenly clicking the button when they intend to activate the div. I believe this can be resolved using event handling techniques described here: https://v2.vuejs.org/v2/guide/events.html#Event-Modifiers, but I am struggling to implement it successfully.

You can view the codepen example at the following URL: https://codepen.io/jameshine/pen/GRNNzdq or see the code snippet below.

Note: If you test this on a desktop and click the button, you will still receive the "clicked by mistake" error message. This codepen is optimized for mobile views, but I'm unsure if I can replicate the problem accurately on mobile devices.

<div id="app">
  <div class="container mx-auto">
    <div class="flex -mx-2">
      <div class="w-1/2 px-2" @mouseenter="activate(key)" v-for="(item, key) in items" :key="key">
        <div class="h-full p-5 rounded-lg" :class="[ active === key ? 'bg-yellow-500' : 'bg-gray-300']">
          <div class="mb-10">
            <p>{{ item.name }}</p>
          </div>

          <button class="bg-red-500 px-3 py-2 rounded" @click="alert('I\'ve been clicked by mistake')" v-if="active === key">Activate Me</button>
        </div>
      </div>
    </div>
  </div>
</div>
new Vue({
  el: "#app",

  data() {
    return {
      active: undefined,
      items: [
        {
          name: "A"
        },
        {
          name: "B"
        }
      ]
    };
  },
  methods: {
    activate(key) {
      this.active = key;
    }
  }
});

Answer №1

It seems like you're looking for a solution to a particular issue. Here is one way to approach it:

<button @click.prevent.stop="handleClick(key)">Activate me</button>

// Methods:
handleClick(key) {
  if (this.active !== key) {
    this.active = key;
  } else {
    // Implement the desired functionality when clicked again
  }
}

UPDATE 1:

The problem may be related to the mouseenter event triggering just before the click event on mobile devices. One workaround could be introducing a slight delay in your activate method, as shown below:

activate(key) {
  setTimeout(() => this.active = key, 50);
}

UPDATE 2:

Another solution involves adding the following to the parent div:

@touchstart.prevent="handleTouchStart($event, key)"

Then, in your methods:

handleTouchStart($event, key) {
  if (this.active === key) {
    $event.target.click();
  } else {
    this.active = key;
  }
}

This setup ensures that when a touchStart event occurs on the parent div, it either cancels the event and makes the div active if it's not currently so, or allows the click event to proceed if it is already active.

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

Ways to retain the page state even after refreshing or quitting the browser?

I am in the process of developing a quiz application that utilizes Laravel for the backend and Vue.js for rendering questions on the frontend. One issue I'm grappling with is how to maintain the quiz's state even if a candidate reloads the page o ...

Modify mouse pointer when an object is clicked using JavaScript

Greetings, I am in the process of designing a website for a client. I have encountered a challenge in changing the cursor icon when a user performs a mousedown on an object. There is an image on the webpage When the user clicks on the image, the cursor s ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Converting a JavaScript object into JSON format

I am currently working on serializing a JavaScript object to JSON. Here is the code I have written so far: var info = {}; ... $.each(data, function (key, value) { info["name"] = value.name; info["id"] = value.id; ...

The specified type `Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>` is not compatible with `Observable<HttpResponse<Pet>>`

I'm currently attempting to integrate the Angular code generated by openapi-generator with the JHipster CRUD views. While working on customizing them for the Pet entity, I encountered the following error: "Argument of type 'Observable & ...

Implementing cross-app module injection in Node.js

I have two node apps/services that are currently running together: 1. the main app 2. the second app The main app is responsible for displaying all the data from different apps in the end. Currently, I have taken some code from the second app and integra ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query const createUserClass = async (event) => { event.preventDefault(); try { const { data } = await createType({ ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...

Add a sub-modal window inside a separate container

Is there a way to attach this modal to an external div? The current setup involves nesting it within a container that has a fixed height. I'm looking to move it outside of that container. Here is the JavaScript code for the modal: client.fetchQuery ...

How to extract various arrays of identical objects from a larger array in JavaScript

I am working with an array containing objects of this structure: {id: 543, firstName: 'Ted', lastName: 'Foo', age: 32} My goal is to filter out objects in the array that have the same values for both the firstName and age properties. ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

The PHP function is not successfully receiving a value from the AJAX call to be entered into the Database

I've been struggling with a piece of code lately, trying to pass the value 1 to my database when a user clicks the "collect coins" button. The goal is to reset the column "dailyfree" every day at 12 pm so that users can click the button again on the n ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Steps for breaking down a given string into divisions that correspond to an A4 sheet

Within my content, there are various styles applied. For example: This is a <b>bolded</b> word. I am seeking a solution to divide this long string into smaller sections that would fit on an A4 page accurately. The goal is to maintain the integ ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...